Laravel 5.6 DB::RAW count() - laravel

How do I count the number of rows in score column where score is less than 50?
$user = DB::table('users')
->leftJoin('rankings', 'rankings.user_id', '=', 'users.id')
->select('users.*', DB::raw("( (count(rankings.score) ) ) as `countBelow50` ")

Check for the advanced join clauses: https://laravel.com/docs/5.7/queries#joins
$user = DB::table('users')
->leftJoin('rankings', function($join) {
$join->on('rankings.user_id', '=', 'users.id')
->where('rankings.score','<','50');
})
->select('users.*', DB::raw("( (count(rankings.score) ) ) as `countBelow50` ")

Related

Laravel Eloquent Subquery with condition

How to add a subquery to the main query with a condition? The result of the request should be similar to this:
select
`tasks`.*,
`users`.`name` as `user_name`,
(select count(*) from tasks_favorites on tasks_favorites.task_id = tasks.id and tasks_favorites.user_id = 38) as `is_favorite`
from `tasks`
left join `users` on `users`.`id` = `tasks`.`user_id`
where
`tasks`.`id` = 149
I try this query but I get an error:
$task = DB::table('tasks')
->select(
'tasks.*',
'users.name as user_name',
)
->when(Auth::check(), function($query) {
return $query->addSelect(
DB::table('tasks_favorites')->where('tasks_favorites.task_id', 'tasks.id')->where('tasks_favorites.user_id', auth()->user()->id)->count()
) ;
})
->leftJoin('users', 'users.id', 'tasks.user_id')
->where('tasks.id', $task_id)
->get()
->first() ;
did you try the selectRaw or raw method?
something like this
$task = DB::table('tasks')
->select(
'tasks.*',
'users.name as user_name',
)
->when(Auth::check(), function($query) {
return $query->addSelect(
DB::raw('select count(id) from tasks_favorites where tasks_favorites.task_id=tasks.id AND tasks_favorites.user_id='.auth()->user()->id.' as mycount')
);
})
->leftJoin('users', 'users.id', 'tasks.user_id')
->where('tasks.id', $task_id)
->get()
->first() ;

How to join two queries as one in whereIn

In my Laravel-5.8 I have these queries:
$manager = DB::table('hr_employees')
->select('line_manager_id')
->where('hr_status',0)
->whereIn('employee_code', $employee_with_goals)
->get();
$employee_with_goals = DB::table('hr_employees')
->join('appraisal_goals', 'hr_employees.employee_code', '=', 'appraisal_goals.employee_code')
->select('hr_employees.employee_code')
->where('hr_employees.company_id', $userCompany)
->where('hr_employees.hr_status',0)
->where('appraisal_goals.is_published', '=', '1')
->where('appraisal_goals.is_approved', '=', '3')
->groupBy('hr_employees.employee_code')
->get();
$manager is the main query
How do I combine these two queries as one using $employee_with_goals as the variable in whereIn()?
You can use the pluck method to retrieve all values for a given key in a collection:
$manager = DB::table('hr_employees')
->select('line_manager_id')
->where('hr_status',0)
->whereIn('employee_code', $employee_with_goals->pluck('employee_code'))
->get();
You can actually use a subquery too:
$manager = DB::table('hr_employees')
->select('line_manager_id')
->where('hr_status',0)
->whereIn('employee_code', function ($query) use ($userCompany) {
$query
->table('hr_employees')
->select('hr_employees.employee_code')
->join('appraisal_goals', 'hr_employees.employee_code', '=', 'appraisal_goals.employee_code')
->where('hr_employees.company_id', $userCompany)
->where('hr_employees.hr_status',0)
->where('appraisal_goals.is_published', '=', '1')
->where('appraisal_goals.is_approved', '=', '3')
->groupBy('hr_employees.employee_code')
})
->get();
The code above is untested.

Select unique records from child with condition on parent relationship

I have two tables, Shows and Episodes, each episode has show_id linking them one to many.
Now I need to get latest 6 episodes, one per show, where show.active is true
I've tried the following code:
$episodes = Episode::select(DB::raw('t.*'))
->from(DB::raw('(SELECT * FROM episodes ORDER BY id DESC) t'))
->whereHas('show', function($query) {
$query->where('active', '=', true);
})
->groupBy('t.show_id')
->take(6)
->get();
Unfortunately, I get the following:
Column not found: 1054 Unknown column 'episodes.show_id' in 'where clause' (SQL: select t.* from (SELECT * FROM episodes ORDER BY id DESC) t where exists (select * from shows where episodes.show_id = shows.id and active = 1) group by t.show_id limit 6)
I've also tried:
$episodes = Episode::where('active', true)
->orderBy('id', 'DESC')
->whereHas('show', function($query) {
$query->where('active', '=', true);
})
->groupBy('show_id')
->take(6)
->get();
It shows no error, but doesn't return latest of each show, groupBy gets the first record, I need the latest
This should work:
$episodes = Episode::where('active', true)
->whereHas('show', function($query) {
$query->where('active', '=', true);
})
->groupBy('show_id')
->orderBy('id', 'DESC')
->take(6)
->get();
You can try this
$episodes = Episode::selectRaw('max(id) as id, show_id')
->whereHas('show', function($query) {
$query->where('active', '=', true);
})
->orderBy('id', 'DESC')
->groupBy('show_id')
->take(6)
->get();
You can use a WHERE IN subquery:
$ids = Episode::selectRaw('max(id)')
->whereHas('show', function ($query) {
$query->where('active', '=', true);
})->groupBy('show_id');
$episodes = Episode::whereIn('id', $ids)
->take(6)
->get();

Convert SQL into Laravel Eloquent

I have this SQL query:
SELECT
m1.id
FROM
messages m1
WHERE
m1.to_id = 1 AND m1.created_at < (
SELECT
m2.created_at
FROM
messages m2
WHERE
m2.from_id = m1.to_id AND m2.to_id = m1.from_id)
GROUP BY
m1.id
How can i convert into eloquent? I done this until now, but a don't know what to do in the part of where on subquery.
Message::where('to_id', 1)
->where('created_at', '<', function($q) {
$q->from('messages');
$q->select('created_at');
})
->select('id')
->groupBy('id')
->get();
You can try this:
Message::where('to_id', 1)
->where('created_at', '<', function($q) {
$q->from('messages AS m2')
->select('created_at')
->where('m2.from_id ','=', 'messages.to_id ')
->where('m2.to_id','=','messages.from_id');
})
->select('id')
->groupBy('id')
->get();

Laravel 5.2 : How to write query builder with 2 ON in this right join

I have this sql syntax
SELECT vehicles.license_plate, vehicles.year, vehicles.status, vehicles.zone_id, vehicles.car_class_id, harga_sewa.value, harga_sewa.description
FROM `vehicles`
RIGHT JOIN `harga_sewa` ON vehicles.zone_id = harga_sewa.zone_id
AND vehicles.car_class_id = harga_sewa.car_class_id
How I can write something like this?
DB::table('vehicles')
->rightJoin('harga_sewa', 'vehicles.zone_id', '=', 'harga_sewa.zone_id', AND vehicles.car_class_id = harga_sewa.car_class_id)
->select(*)
Try below code
DB::table('vehicles')
->rightJoin('harga_sewa', function ($join) {
$join->on('vehicles.zone_id', '=', 'harga_sewa.zone_id');
$join->on('vehicles.car_class_id', '=', 'harga_sewa.car_class_id');
})
->get();
On mobile, so can't test, but from memory this should work:
DB::table('vehicles')
->rightJoin('harga_sewa', 'vehicles.zone_id', '=', 'harga_sewa.zone_id')
->rightJoin('harga_sewa', 'vehicles.car_class_id', '=', 'harga_sewa.car_class_id')
->select('*')
->get();

Resources