我想知道基于我的数据库结构的排名:
我有一个模型Post
,它属于一个名为Edition
的模型(也是一个 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();
对于不熟悉 Laravel Eloquent ORM
的人,我报告一下上面代码执行的 sql 查询:
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
的记录的行位置?
例如,如何获取id = 132
记录的排名结果?
最佳答案
您可以使用子查询:
$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));
});
关于php - Eloquent/SQL - 获取查询的行号(排名),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55363173/