gpt4 book ai didi

php - Eloquent/SQL - 获取查询的行号(等级)

转载 作者:行者123 更新时间:2023-11-29 02:39:41 27 4
gpt4 key购买 nike

我想知道基于我的数据库结构的排名:

我有一个模型 Post 属于一个名为 Edition 的模型(也是 one Edition 有很多 Post).

一个Post有很多Like

我想根据特定 Edition 中的 Like 计数知道 Post 的排名。

代码:

// 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com