I want to get unique posts ordering by project_id
, basically, if there are duplicated posts I want the one in which project_id
is not null. Is there any way to get this?
This code is returning unique posts, but they are not ordered by 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']);
}
If I remove the groupBy
, I got duplicated posts ordered by project_id
.
The output of 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
Below I show the results that I got and the result I desire:
I removed the additional data for better reading
Result with groupBy
and orderBy
clauses. Unique posts but not ordered by 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
}
}
],
Result without groupBy
clause. Duplicated posts ordered by 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
}
}
],
Result I desire. Unique posts ordered by 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
}
}
],
I thank you for taking the time to help me.