How can I perform a sub query in eloquent?
I need to convert:
select * from(//complex sub query) as prds order by date desc
How can I perform a sub query in eloquent?
I need to convert:
select * from(//complex sub query) as prds order by date desc
It's tricky to answer this without the specific tables, columns, etc. But in general, the key to doing this kind of thing is that you can pass a function as the second parameter of whereIn()
or whereExists()
, and that will create a sub-query. For example:
Products::whereExists(function ($query) {
$query->select(DB::raw(1))->from('orders')
->whereRaw('orders.product_id = products.id');
})->get();
Or you can do something with whereIn() like this:
Products::whereIn('id', function ($query) use ($orderID) {
$query->select('product_id')->from('orders')
->where('orders.id', $orderID);
})->get();
At first create subquery that you need
$subQuery = DB::table("some_table as s")
->select('s.name', DB::raw('count(s.id) as s_count'))
->join('other_table as o', 's.id', '=', 'o.val')
->where('o.values', $someVal)
->groupBy('s.name');
Than can create general query
$rows = DB::table(DB::raw("({$subQuery->toSql()}) as sub"))->mergeBindings($subQuery)
->where('sub.name', $val)
->orderBy("sub.s_count", 'asc')
->get();
Also you can get count if need
$count = DB::table(DB::raw("({$subQuery->toSql()}) as sub"))->mergeBindings($subQuery)
->where('sub.name', $val)
->count();