我想按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
}
}
],
我感谢您抽出宝贵的时间来帮助我。
答案 0 :(得分:0)
检索posts
时,将返回一个集合。
然后您可以使用->sortByDesc()
collection method以降序对结果进行排序(使用自定义逻辑):
$posts = $service->posts
->sortByDesc(function ($post, $key) {
return $post['pivot']['project_id'];
})
->values()
->all();
此处,posts
由post_id
的枢轴点post
按降序排序(不确定是否通过->
语法或数组键访问它,就像我之前所说的那样)尚未测试)。
要删除所有重复项(检查project_id
是否为空),请使用-wherePivot()
:
public function posts()
{
return $this->belongsToMany('App\Post')
->withPivot('id', 'unity', 'coefficient', 'project_id')
->wherePivot('project_id', '=!', null)
->orderBy('project_id', 'DESC')
->groupBy(['post_id']);
}