简体   繁体   中英

Laravel - Get the most recently created rows for a variety of IDs, from an array

I need a Laravel query that returns the most recently created row of various site_id rows please. At the moment, I have this query:

Score::whereIn('site_id', $sites)->where('type', 2)->select('score')->get();

But it's returning all of the scores for the sites, where type = 2.

At the moment, the $sites array only contains 1,2 , so it will exclude the site_ids that are 3 and 4.

Database structure:

数据库结构

My intended result that the query returns would be the following rows:

ID: 1, 2. - As in, they are the most recently created rows of the IDs within the array.

Update:

If I use:

Score::whereIn('site_id', $sites)->where('type', 2)
            ->select('score')
            ->groupBy('site_id')
            ->get();

a groupBy method, it returns the two scores that I want, but I'm not sure why it would return them? I thought it would just group all of the site's scores by site_id?

Thank you for your help.

我觉得您只需要将orderBy(“ created_at”)链接到雄辩的查询末尾即可。

Here's what you need: https://softonsofa.com/tweaking-eloquent-relations-how-to-get-latest-related-model/

With that you can easily do this:

$sites = Site::with('latestScore')->find($siteIds); // Collection
// now for each site:
$site->latestScore // what you wanted

however, if you want a collection of scores instead of accessing them via site , then use collection methods:

$sites = Site::with('latestScore')->find($siteIds); // Collection
$scores = $sites->pluck('latestScore') // get nested elements from collection
                ->filter() // filter out null items

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