Laravel Eloquent 按 created_at 排序 post 并保持置顶 post

Laravel Eloquent order posts by created_at and keep sticky post on Top

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

Sticky post 是 sticky_post 列在 post 数据库中 的位置

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

Post架构如下:

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在数据库中表示为一个1TINYINT(1)),所以所有的置顶帖都会按降序排列。任何具有相同 sticky_post 值的记录将按 created_at 列排序。

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