Laravel - 从数组中获取各种 ID 最近创建的行
Laravel - Get the most recently created rows for a variety of IDs, from an array
我需要一个 Laravel 查询 return 是各种 site_id
行中最近创建的行。目前,我有这个查询:
Score::whereIn('site_id', $sites)->where('type', 2)->select('score')->get();
但它 return 计算网站的所有分数,其中类型 = 2。
目前,$sites
数组只包含1,2
,所以它会排除site_ids,即3和4。
数据库结构:
我的预期结果是查询 returns 将是以下行:
ID: 1, 2. - 就像,它们是数组中最近创建的 ID 行。
更新:
如果我使用:
Score::whereIn('site_id', $sites)->where('type', 2)
->select('score')
->groupBy('site_id')
->get();
一个groupBy
方法,它return是我想要的两个分数,但我不确定为什么会return它们?我认为它只会按 site_id?
对网站的所有分数进行分组
感谢您的帮助。
我觉得您只需要一个链接到 eloquent 查询末尾的 orderBy("created_at")。
这是您需要的:https://softonsofa.com/tweaking-eloquent-relations-how-to-get-latest-related-model/
有了它,您可以轻松做到这一点:
$sites = Site::with('latestScore')->find($siteIds); // Collection
// now for each site:
$site->latestScore // what you wanted
但是,如果您想要收集乐谱而不是通过 site
访问它们,请使用收集方法:
$sites = Site::with('latestScore')->find($siteIds); // Collection
$scores = $sites->pluck('latestScore') // get nested elements from collection
->filter() // filter out null items
我需要一个 Laravel 查询 return 是各种 site_id
行中最近创建的行。目前,我有这个查询:
Score::whereIn('site_id', $sites)->where('type', 2)->select('score')->get();
但它 return 计算网站的所有分数,其中类型 = 2。
目前,$sites
数组只包含1,2
,所以它会排除site_ids,即3和4。
数据库结构:
我的预期结果是查询 returns 将是以下行:
ID: 1, 2. - 就像,它们是数组中最近创建的 ID 行。
更新:
如果我使用:
Score::whereIn('site_id', $sites)->where('type', 2)
->select('score')
->groupBy('site_id')
->get();
一个groupBy
方法,它return是我想要的两个分数,但我不确定为什么会return它们?我认为它只会按 site_id?
感谢您的帮助。
我觉得您只需要一个链接到 eloquent 查询末尾的 orderBy("created_at")。
这是您需要的:https://softonsofa.com/tweaking-eloquent-relations-how-to-get-latest-related-model/
有了它,您可以轻松做到这一点:
$sites = Site::with('latestScore')->find($siteIds); // Collection
// now for each site:
$site->latestScore // what you wanted
但是,如果您想要收集乐谱而不是通过 site
访问它们,请使用收集方法:
$sites = Site::with('latestScore')->find($siteIds); // Collection
$scores = $sites->pluck('latestScore') // get nested elements from collection
->filter() // filter out null items