我想根据我的数据库结构了解排名:
我有一个模型Post
属于一个名为Edition
的模型(也一个 Edition
有很多 {{1 }}。
一个Post
有很多Post
。
我想根据特定Like
内的Post
个计数来了解Like
的排名。
代码:
Edition
对于不熟悉// 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();
的人,我报告从上面的代码执行的sql查询:
Laravel Eloquent ORM
我报告查询结果:
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
如何从组合查询的结果中获取具有特定=> 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,
},
],
}
的记录的行位置?
例如,如何使用id
检索记录的排名结果?
答案 0 :(得分:1)
您可以使用子查询:
$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);
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));
});
答案 1 :(得分:0)
您可以使用search()方法来找到密钥:
搜索方法在集合中搜索给定的值,如果找到,则返回其键。如果找不到该项目,则返回false。
$id = 132;
$key = $query->search(function($post,$id) {
return $post->id === $id;
});