Reputation: 3488
I would like to know the rank based on my DB structure:
I have a model Post
that belongs to a model called Edition
(also one Edition
has many Post
).
One Post
has many Like
.
I would like to know the rank of a Post
based on the Like
count inside a particular Edition
.
The code:
// Define the id of an edition
$edition_id = 53;
// The id of the post to retrieve rank
$post_id = 132;
// Compose the query by select all posts, of interested edition ...
$query = App\Models\Post::where('edition_id', $edition_id)
// ... with like count (this produce an additional field named likes_count) ...
->withCount('likes')
// ... in descendig order by this count.
->orderBy('likes_count', 'desc');
// By execute it I can get right results.
$query->get();
For people who are not familiar with Laravel Eloquent ORM
, I report the sql query executed from code above:
select `posts`.*, (select count(*) from `likes` where `posts`.`id` = `likes`.`post_id` and `likes`.`deleted_at` is null) as `likes_count`
from `posts`
where `edition_id` = '53' and `posts`.`deleted_at` is null
order by `likes_count` desc
I report the query results:
=> Illuminate\Database\Eloquent\Collection {#994
all: [
App\Models\Post {#993
id: 135,
likes_count: 4,
},
App\Models\Post {#1075
id: 134,
likes_count: 3,
},
App\Models\Post {#1091
id: 133,
likes_count: 2,
},
App\Models\Post {#997
id: 132,
likes_count: 1,
},
App\Models\Post {#1038
id: 131,
likes_count: 0,
},
],
}
How can I get the row position of the record with a certain id
from the results of the composed query?
For example, how to retrieve the rank result of the record with id = 132
?
Upvotes: 2
Views: 2735
Reputation: 25906
You can use a subquery:
$query = Post::where('edition_id', $edition_id)
->withCount('likes')
->selectRaw('@rank := @rank + 1 rank')
->from(DB::raw('`posts`, (SELECT @rank := 0) vars'))
->orderBy('likes_count', 'desc');
$posts = Post::fromSub($query, 'posts')->paginate();
$post = Post::fromSub($query, 'posts')->find($post_id);
Workaround for Laravel < 5.6:
Builder::macro('fromSub', function($query, $as) {
$this->bindings = array_merge(
array_slice($this->bindings, 0, 1),
['from' => $query->getBindings()],
array_slice($this->bindings, 1)
);
$sql = '('.$query->toSql().') as '.$this->grammar->wrap($as);
return $this->from(DB::raw($sql));
});
Upvotes: 2
Reputation: 2636
You can use the search() method to find the key:
The search method searches the collection for the given value and returns its key if found. If the item is not found, false is returned.
$id = 132;
$key = $query->search(function($post,$id) {
return $post->id === $id;
});
Upvotes: 0