我最初的查询搜索了主板,然后找到了主板的图像。但现在,一些主板没有任何图像关联,所以我想运行一个查询,可以找到20个独特的主板与图像。
目前为止的代码:
$newMotherboards = Motherboards::join('images', 'motherboards.motherboard_id', '=', 'images.item_id')
->where('images.item_type', '=', 'motherboard')
->orderBy('motherboards.date_added', 'desc')
->take(20)
->get();我甚至试着选择具体的结果:
$newMotherboards = Motherboards::join('images', 'motherboards.motherboard_id', '=', 'images.item_id')
->select('motherboards.motherboard_id', 'motherboards.name')
->where('images.item_type', '=', 'motherboard')
->orderBy('motherboards.date_added', 'desc')
->take(20)
->get();上面的代码的问题是,当我循环遍历每个$newMotherboards时,它对每一个有ID的图像都有重复。我只想检索20个唯一的主板,它们是最近添加的,但是有图像。
如果一个项目有5个图片,并且是最近增加的20个图片之一,那么它将出现在我的20倍限制的五倍。
发布于 2015-03-04 09:35:43
不同版本:
$newMotherboards = Motherboards::join('images', 'motherboards.motherboard_id', '=', 'images.item_id')
->select('motherboards.motherboard_id', 'motherboards.name')
->where('images.item_type', '=', 'motherboard')
->distinct()
->orderBy('motherboards.date_added', 'desc')
->take(20)
->get();Groupby版本:
$newMotherboards = Motherboards::join('images', 'motherboards.motherboard_id', '=', 'images.item_id')
->select('motherboards.motherboard_id', 'motherboards.name')
->where('images.item_type', '=', 'motherboard')
->groupby('images.item_type')
->orderBy('motherboards.date_added', 'desc')
->take(20)
->get();https://stackoverflow.com/questions/28849719
复制相似问题