gpt4 book ai didi

laravel - 查找过去 24 小时内帖子最高的用户,laravel Eloquent

转载 作者:行者123 更新时间:2023-12-01 10:20:08 25 4
gpt4 key购买 nike

如何在laravel中找到过去24小时内创建的帖子最高的用户?
按帖子数量降序排列。

最佳答案

如果我没记错的话,您是在询问在过去 24 小时内创建的帖子数量最多的用户。

为此,请执行以下操作:

$users = User::withCount(['posts' => function ($query) {
$query->where('created_at', '>=', carbon()->now()->subDay());
}])->orderBy('posts_count', 'DESC')
->get();

documentation状态,您可以向查询添加约束。

Counting Related Models

If you want to count the number of results from a relationship without actually loading them you may use the withCount method, which will place a {relation}_count column on your resulting models. For example:

$posts = App\Post::withCount('comments')->get();

foreach ($posts as $post) {
echo $post->comments_count;
}

You may add the "counts" for multiple relations as well as add constraints to the queries:

$posts = Post::withCount(['votes', 'comments' => function ($query) {
$query->where('content', 'like', 'foo%');
}])->get();

echo $posts[0]->votes_count;
echo $posts[0]->comments_count;

关于laravel - 查找过去 24 小时内帖子最高的用户,laravel Eloquent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53238563/

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