需要帮助从数据库中获取帖子并根据 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/