Php Laravel-在elequent上使用distinct
我想得到最后三个价格(6,7,8)我不需要限制。Php Laravel-在elequent上使用distinct,php,laravel,Php,Laravel,我想得到最后三个价格(6,7,8)我不需要限制。 id:8是对id:5的更新 应显示id:8而不是id:5 [ { id: 5, product_id: 1, seller_id: 26, color_id: 18, warranty_id: 29, price: 1000000, created_at: "2017-05-27 09:33:44", }, {
id:8
是对id:5
的更新
应显示id:8
而不是id:5
[
{
id: 5,
product_id: 1,
seller_id: 26,
color_id: 18,
warranty_id: 29,
price: 1000000,
created_at: "2017-05-27 09:33:44",
},
{
id: 6,
product_id: 1,
seller_id: 26,
color_id: 19,
warranty_id: 30,
price: 1200000,
created_at: "2017-05-27 09:33:56",
},
{
id: 7,
product_id: 1,
seller_id: 26,
color_id: 21,
warranty_id: 33,
price: 900000,
created_at: "2017-05-27 09:34:06",
},
{
id: 8,
product_id: 1,
seller_id: 26,
color_id: 18,
warranty_id: 29,
price: 600000,
created_at: "2017-05-27 10:21:23",
}
]
我的尝试:
$product->get_prices()
->groupby(['product_id','color_id','warranty_id','seller_id'])
->latest()
->get();
// 5,6,7,8
Product.php
function get_prices(){
return $this->hasMany('\App\Price');
}
收藏版
您可以在此处使用unique()
。作为唯一值,我使用了给定id(卖方、产品、保修和颜色id)和分隔符(您可以根据需要更改分隔符)的组合
我以前使用过reverse()
函数,因此unique函数将返回最后一个副本,而不是第一个副本
然后像往常一样转到take()
)
您也可以在使用给定的解决方案之前发出有说服力的查询:
$product->get_prices()->with("...")->where("....")
->get()->reverse()->unique(function ($item) {
return $item['product_id'] . "|" . $item['seller_id'] . "|" .
$item['color_id'] . "|" . $item['warranty_id'];
})->take(3);
ORM版本? 我已经尝试了很多,以获得一个工作的ORM版本,但不幸的是,我无法创建一个。 如果您真的想在DB层上执行此操作,我想最好使用原始查询 相关的:
请不要将代码作为图像发布。但是。我们不能用orm做这件事?(在orm上)好吧,在orm上更难做到这一点,在IMO上就更难做到了。我确信只有雄辩才能做到这一点,但我不认为它的性能更好。请看我的更新,我更喜欢在ORM@danialdezfooli更新了我使用ORM的答案again@danialdezfooli不幸的是没有。无论如何,我补充了一个相关的问题。因此,也许一个原始查询就足够了。
$product->get_prices()->with("...")->where("....")
->get()->reverse()->unique(function ($item) {
return $item['product_id'] . "|" . $item['seller_id'] . "|" .
$item['color_id'] . "|" . $item['warranty_id'];
})->take(3);