我想获得唯一的帖子排序project_id
,基本上,如果有重复的帖子,我想要一个project_id
不为空的帖子。有没有办法得到这个?
此代码返回唯一的帖子,但它们不是按 排序的project_id
。
/**
* Get the posts record associated with the service.
*/
public function posts()
{
return $this->belongsToMany('App\Post')
->withPivot('id', 'unity', 'coefficient', 'project_id')
->orderBy('project_id', 'DESC')
->groupBy(['post_id']);
}
如果我删除groupBy
,我会得到由 . 排序的重复帖子project_id
。
的输出dd($service->posts()->toSql());
:
select * from `posts`
inner join `post_service` on `posts`.`id` = `post_service`.`post_id`
where `post_service`.`service_id` = ?
group by `post_id`
order by `project_id` desc
下面我展示了我得到的结果和我想要的结果:
我删除了附加数据以便更好地阅读
结果与groupBy
和orderBy
子句。独特的帖子,但未按以下顺序排序project_id
:
"posts": [
{
"id": 733,
"pivot": {
"service_id": 20177,
"post_id": 733,
"id": 2575,
"project_id": null
}
},
{
"id": 725,
"pivot": {
"service_id": 20177,
"post_id": 725,
"id": 2576,
"project_id": null
}
}
],
结果无groupBy
子句。重复的帖子按以下顺序排序project_id
:
"posts": [
{
"id": 733,
"pivot": {
"service_id": 20177,
"post_id": 733,
"id": 9723,
"project_id": 4
}
},
{
"id": 733,
"pivot": {
"service_id": 20177,
"post_id": 733,
"id": 2575,
"project_id": null
}
},
{
"id": 725,
"pivot": {
"service_id": 20177,
"post_id": 725,
"id": 2576,
"project_id": null
}
}
],
我想要的结果。独特的帖子按以下顺序排序project_id
:
"posts": [
{
"id": 733,
"pivot": {
"service_id": 20177,
"post_id": 733,
"id": 9723,
"project_id": 4
}
},
{
"id": 725,
"pivot": {
"service_id": 20177,
"post_id": 725,
"id": 2576,
"project_id": null
}
}
],
我感谢你花时间帮助我。