php - Eloquent/SQL - 获取查询的行号(排名)

标签 php mysql sql laravel eloquent

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

我有一个模型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/

相关文章:

php - 为什么我调用函数时不加载 View ?代码点火器

php - 使用 PHP 将文件上传到 MySql 数据库

php - Symfony2 : Retrieve app. 来自命令的 Twig 请求

c++ - 在 C++/boost 中将日期时间转换为不同的时区

mysql - 每个派生表都必须有自己的别名 - *每个*派生表还是仅在每个查询中?

mysql - 计算不同的值

sql - 在配置单元的指定条件下从单行创建多行

sql - 如何重写长查询?

sql - SQL 中的 DUM 和 DEE 差异

php - 这是一个好的博客结构吗?