I have write a query for fetch every users his/her last organization name, but it's only return organization table last organization name. how can i develop this query for every users.
Here is my Query.
$org=DB::table('careers')
->join('users','careers.user_id','=','users.id')
->pluck('org_name')
->last();
print_r($org);
You can use latest() and first() method for getting last 1 record
$org=DB::table('careers')
->join('users','careers.user_id','=','users.id')
->latest()
->first()
->pluck('org_name');
OR
use latest() and take() method
$org=DB::table('careers')
->join('users','careers.user_id','=','users.id')
->latest()
->take(1)
->pluck('org_name');
Use DB::raw to get the records.
$org=DB::raw("SELECT users.name, t.org_name
FROM users JOIN (SELECT org_name
FROM careers
WHERE users.id = careers.user_id
ORDER BY created_at DESC
LIMIT 1) as t ON t.user_id = user.id");
Hope this could work.
Related
this is my sql query
SELECT COUNT(*) FROM anuncios WHERE user_id = 2 and user_id = 3 or estado = "Activo" GROUP BY user_id
results in the total number of active "anunios" for each user_id;
but trying the same query with laravel eloquent brings me the total of all the data without grouping them by user_id
this is my query with laravel eloquent
$anuncios = Anuncios::whereIn('user_id',$ids)->where('estado','Activo')->groupBy('user_id')->get()->count();
If you are calling ->get() you are doing a count() on a Collection. If you want to run it as a query, you need to call it on a QueryBuilder by removing the ->get().
To achieve it in pure Eloquent, you can use the following:
$anuncios = Anuncios::select('user_id','estado')
->whereIn('user_id',$ids)
->where('estado','Activo')
->groupBy('user_id')
->count();
I am trying to get the data on some students that are still active. Even tho I have data from inactive students in the same table.
This is the StudentAttendance
This is the StudentClass
This is the Eloquent query that I came up with:
StudentAttendance::
select('student_classes.active', 'student_attendances.student_id', 'student_attendances.classroom_id', 'classrooms.classroom', 'attendance_rules.option')
->join('classrooms', 'classrooms.id', '=', 'student_attendances.classroom_id')
->join('attendance_rules','attendance_rules.id', '=', 'student_attendances.attendance_id')
->join('student_classes', 'student_attendances.student_id', '=', 'student_classes.student_id')
->where('attendance_date', date("Y-m-d"))
->orderBy('classrooms.classroom', 'ASC')
->get();
SQL:
select `student_classes`.`active`, `student_attendances`.`student_id`, `student_attendances`.`classroom_id`, `classrooms`.`classroom`, `attendance_rules`.`option`
from `student_attendances`
inner join `classrooms` on `classrooms`.`id` = `student_attendances`.`classroom_id`
inner join `attendance_rules` on `attendance_rules`.`id` = `student_attendances`.`attendance_id`
inner join `student_classes` on `student_attendances`.`student_id` = `student_classes`.`student_id`
where `attendance_date` = '2020-02-11'
order by `classrooms`.`classroom` asc
Now my Eloquent query results into this:
As you can see the student_id 22 with the classroom_id of 2 is inactive but it appears to be inactive once and the rest active. If I remove the student_classes join I won't get all the repeated results.
The goal is to display all the attendances of today where the student is active (active=1) in the StudentClass even if I query in the StudentAttendance.
You will want to scope your join to student_classes to only look at active records.
You can do this by using a callback in your join method:
->join('student_classes', function ($join) {
$join->on('student_attendances.student_id', '=', 'student_classes.student_id')
->on('student_classes.classroom_id', '=', 'student_attendances.classroom_id')
->where('student_classes.active', 1);
})
This is covered under the 'Advanced Join Clauses' in the Query Builder docs - https://laravel.com/docs/5.8/queries#joins
I tried this query but it only order id column, rest is not.
$chapters = Test::select(DB::raw('*, max(id) as id'))
->groupBy('id_equip')
->orderBy('id', 'asc')
->get();
In MySQL when using group by you can't rely on order by clause (it won't work as you expect, ie. it will not order the results in groups, but rather return random row from the group).
So in order to achieve what you want, you need a subquery or join:
// assuming tests table, group by id_equip, order by id
SELECT * FROM tests WHERE id = (
SELECT MAX(id) FROM tests as t WHERE t.id_equip = tests.id_equip
) ORDER BY id
SELECT * FROM tests
JOIN (SELECT MAX(id) as id FROM tests ORDER BY id DESC) as sub
ON sub.id = tests.id
This will get the highest id for each id_equip and return whole row for each of them.
Now, in eloquent I suggest first approach, if you want it to look more intuitive:
Test::where('id', function ($sub) {
// subquery
$sub->selectRaw('max(id)')
->from('tests as t')
->where('t.id_equip', DB::raw('tests.id_equip'));
// order by
})->orderBy('id', 'desc')->get();
but 2nd appreach is probably the way if you have big table to scan (in terms of performance):
Test::join( DB::raw(
'(select max(id) as id from tests group by id_equip order by id desc) sub'
), 'sub.id', '=', 'posts.id')
->get(['tests.*']);
Here you need to set order by clause inside the raw join statement.
You could also build that join subquery with the builder if you like:
$sub = Test::selectRaw('max(id)')
->groupBy('id_equip')
->orderBy('id', 'desc')
->toSql();
Test::join( DB::raw(
"({$sub}) as sub"
), 'sub.id', '=', 'posts.id')
->get(['tests.*']);
I'm trying to do a left join using two tables, where I need to get all user id and name in first which satisfies a condition and total number of rows in the second table for each user. If a user doesn't have a row in the second table, it must be null or zero.
This is my eloquent query.
$users->where('users.access_type', '=', 'type1')->orwhere('users.access_type', '=', 'type2')
->leftJoin(DB::raw("(SELECT user_id, COUNT(*) as count FROM table2 WHERE date > '2014-09-17 16:30:04' GROUP BY user_id) temp_table"), function($leftJoin) {
$leftJoin->on('temp_table.user_id', '=', 'users.user_id');
})->select(DB::raw('users.user_id, users.name, temp_table.count as count'))->orderBy('count')->get();
which doesn't returns the user with null count value. instead it returns the user with least count. I printed the query log and copied the raw query for the above query, filled the values and executed. which works perfectly and also returns the user with null entries. No changes made to the query obtained from query log other than adding the values. Copying the raw query below.
select users.user_id, users.name, temp_table.count as count from `users` left join (SELECT user_id, COUNT(*) as count FROM table2 WHERE date > '2014-09-17 16:30:04' GROUP BY user_id) temp_table on `temp_table`.`user_id` = `users`.`user_id` where `users`.`access_type` = 'type1' or `users`.`access_type` = 'type2' order by `count` asc
I have tried changing the column name of the user_id field for both using as user. Also tries replacing null values with zero using IFNULL. But still no go. Please let me know what am I doing wrong.
In your Eloquent query, you need to replace the last function call ...->first() by ...->get() in order to retrieve all the results instead of only the first one.
I have 2 databases (AccessControls & User).
AccessControl table has this fields: AC_id, User_id, AccessControls.
User table has this fields: User_id, User_name, UserType.
What I wanted to achieve is:
- Printing out users that has a UserType = 1 (in user table) and User_id which does not exist in AccessControl table.
The results will be stored in a table in my view.blade.php
In the meantime, I managed to get the 1st part, which is users with UserType = 1. However, I have no idea on how I could get the 2nd part, which is to check if the User_id exists in AccessControl table.
Inside my controller:
$user = UserEntry::where('UserType', '=', 1)->get();
I have a rough idea that the query should be something like:
Select statement Where user.User_id != AccessControl.User_id
Any ideas on how I could achieve both parts in a single query?
Either not exists
User::where('UserType',1)
->whereNotExists(function ($q) {
$q->from('AccessControl')
->where('AccessControl.User_id', DB::raw('users.id'));
})
->get();
or leftJoin:
User::where('UserType',1)
->leftJoin('AccessControl','AccessControll.User_id','=','users.id')
->whereNull('AccessControll.id')
->get(['users.*']);
Check performance, suppose left join will be faster.
The SQL way would be a LEFT JOIN in combination with ISNULL():
SELECT
*
FROM
users
LEFT JOIN
AccessControl
ON
user.User_id = AccessControl.User_id
WHERE
users.userType = 1
AND
AccessControl.User_id IS NULL
I'm sure you get this translated to laravel.