mysql - Laravel Eloquent order posts by created_at 并保持置顶

标签 mysql laravel eloquent

需要帮助从数据库中获取帖子并根据 created_at 列对它们进行排序,但将 sticky post(就像在 wordpress 帖子系统中一样)保持在顺序的顶部。

Sticky post 是帖子数据库中 sticky_post 列为 true 的地方

public function index(PostFilter $filter)
{
    return Post::with(['author', 'category', 'tags'])
        ->withTrashed()
        ->filter($filter)
        ->paginate(request()->perPage ? request()->perPage : 15);
}

Post Schema 如下:

Schema::create('posts', function (Blueprint $table) {
        $table->increments('id');
        $table->string('slug')->unique();
        $table->string('title');
        $table->text('body')->nullable();
        $table->text('excerpt')->nullable();
        $table->string('category_slug');
        $table->boolean('sticky_post')->default(false);
        $table->dateTime('publish_at')->nullable();
        $table->timestamps();
        $table->softDeletes();

        $table->unsignedInteger('featured_image_id')->nullable();

        $table->unsignedInteger('author_id');
        $table->foreign('author_id')->references('id')->on('users');
    });

感谢您的帮助

最佳答案

orderBy() 是您要找的:

public function index(PostFilter $filter)
{
    return Post::with(['author', 'category', 'tags'])
        ->withTrashed()
        ->filter($filter)
        ->orderBy('sticky_post', 'DESC')
        ->orderBy('created_at', 'DESC')
        ->paginate(request()->perPage ? request()->perPage : 15);
}

true 在数据库中由 1 (TINYINT(1)) 表示,因此所有置顶帖子将按降序。任何具有相同 sticky_post 值的记录都将按 created_at 列排序。

所有置顶帖子将显示在顶部(最新的在前),非置顶的帖子将显示在置顶帖子的下方(最新的在前)。

关于mysql - Laravel Eloquent order posts by created_at 并保持置顶,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47252471/

相关文章:

PHP插入语句只插入1次

mysql - 我怎样才能在MySQL的这张表中度过那几周呢?

mysql - 在 Laravel 中使用 AJAX 从 MySQL 获取数据以进行 API 调用

laravel - base64 : is prepended with Laravel APP_KEY

php - 是否可以使用 Eloquent 方式为模型获取不同模型类型的集合?

mysql - 在 Laravel 中查询多个关系并左连接另一个表

mysql node Select query with JSON information on WHERE statement

mysql - 容器配置和启动的 Docker 依赖设计

Laravel Eloquent 获取分组行的最新行

php - Eloquent: Model::orberBy ('created_at' , 'desc' )->first() 和 Model::all()->last() 之间的区别?