如何首先在 laravel eloquent 中获取最新的 post 和特定的 post id
How to fetch latest posts and specific post id at first in laravel eloquent
有没有办法通过分页获取最新的 post 我还想要一个特定的 post 在返回的集合中排在第一位。
我试过这个...
Post::where(function ($query) {
$query->where('status', 'draft')->orWhere('status', 'published');
})
->orWhere('id', 21)
->with(['author.profile'])
->orderBy('created_at', 'desc')
->paginate(3);
在这个查询中我确实得到了 21
post id 但它在第 3 页上。我想把它放在第一位。请指导我该怎么做。
谢谢
您可以通过在 orderBy 中使用原始语句来实现此目的
Post::orderBy(DB::raw('id = 5'), 'DESC')
->orderBy('created_at', 'desc')
这是因为mysql可以按语句顺序使用布尔表达式
通过使用 eloquent 你会喜欢这样
Post::where('id', '=', 21)->orderBy('created_at','desc')->first();
有没有办法通过分页获取最新的 post 我还想要一个特定的 post 在返回的集合中排在第一位。 我试过这个...
Post::where(function ($query) {
$query->where('status', 'draft')->orWhere('status', 'published');
})
->orWhere('id', 21)
->with(['author.profile'])
->orderBy('created_at', 'desc')
->paginate(3);
在这个查询中我确实得到了 21
post id 但它在第 3 页上。我想把它放在第一位。请指导我该怎么做。
谢谢
您可以通过在 orderBy 中使用原始语句来实现此目的
Post::orderBy(DB::raw('id = 5'), 'DESC')
->orderBy('created_at', 'desc')
这是因为mysql可以按语句顺序使用布尔表达式
通过使用 eloquent 你会喜欢这样
Post::where('id', '=', 21)->orderBy('created_at','desc')->first();