简体   繁体   中英

Laravel LIMIT relation using Eloquent

I have a bunch of Shop s and Item s . Each shop can have a number of different items. However, I want to get all the shops, with only 4 items each.

The following gives me all shops, with all their items:

$shops = Shop::with('items')->get();

The following gives me all shops, but only with 4 items in total , and not each.

$shops = Shop::with(array('items' => function($query) {
    $query->take(4);
}))->get();

How do I get all the shops, with 4 items each?

It's due to an SQL limitation. When eager loading something laravel generate a SQL query that look like

SELECT * FROM xyz WHERE id IN (1, 2...) LIMIT 4;

So the SQL engine return only 4 row at all.

I can't find a quick workaround do to that in laravel. Even in raw SQL it's a problem hard to solve.

Some reading on this subject How to select the first/least/max row per group in sql .

Shop::with(array('items' => function($query) {
    $query->limit(4);
}))->get();

Replacing take with limit should solve your problem.

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