0

我想获得唯一的帖子排序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

下面我展示了我得到的结果和我想要的结果:

我删除了附加数据以便更好地阅读

结果与groupByorderBy子句。独特的帖子,但未按以下顺序排序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
        }
    }
],

我感谢你花时间帮助我。

4

1 回答 1

0

检索posts集合时将返回。

->sortByDesc() 然后,您可以使用集合方法按降序排列结果(使用自定义逻辑):

$posts = $service->posts
    ->sortByDesc(function ($post, $key) {
        return $post['pivot']['project_id'];
    })
    ->values()
    ->all();

在这里,posts它们按枢轴的降序排序post_idpost不确定这是通过->语法还是数组键访问,因为我没有测试过)。

要删除任何重复项(检查是否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']);
}
于 2019-04-11T14:26:09.093 回答