简体   繁体   中英

How can I make select in select on laravel eloquent?

I use laravel 5.3

My sql query is like this :

SELECT * 
FROM (
    SELECT *
    FROM products 
    WHERE `status` = 1 AND `stock` > 0 AND category_id = 5
    ORDER BY updated_at DESC
    LIMIT 4
) AS product
GROUP BY store_id

I want to change it to be laravel eloquent

But I'm still confused

How can I do it?

In cases when your query is to complex you can laravel RAW query syntax like:

$data = DB::select(DB::raw('your query here'));

It will fire your raw query on the specified table and returns the result set, if any.

Reference

If you have Product model, you can run

$products = Product::where('status', 1)
->where('stock', '>', 0)
->where('category_id', '=', 5)
->groupBy('store_id')
->orderBy('updated_at', 'desc')
->take(4)
->get();

I think this should give you the same result since you pull everything from your derived table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM