Laravel订单使用分页器时日期不起作用 [英] Laravel orderBy date is not working when using paginator
问题描述
我是laravel的新手,正在努力弄清这一点.我正在尝试按日期排序帖子,并使用分页器.每当我移除分页器时.它按日期排序,但是我想按ID将其重新添加到订单中?
I am new to laravel and am struggling to figure this one out.I am trying to order my posts by date and also use the paginator. Whenever I remove the paginator. it orders by date, but adding it back in orders by id, I think?
我的模特
class Post extends Model
{
//
protected $dates = ['date'];
}
我的控制器方法
public function show()
{
$posts = Post::orderBy('date','desc')->get();
return view('welcome',['posts' => Post::paginate(5)], compact('posts'));
}
推荐答案
从本质上讲,您是在检索所有帖子并对其进行排序之后,先检索所有帖子,然后对它们进行分页.
You're essentially retrieving all posts and then paginating them, after retrieving all posts and ordering them.
您的代码会像这样分解:
Your code breaks down like this:
public function show()
{
// retrieve posts and order them by date
$posts = Post::orderBy('date','desc')->get();
// retrieve posts again and paginate them
return view('welcome',['posts' => Post::paginate(5)], compact('posts'));
}
您有两个选择-
获取帖子,对其进行排序,对它们进行分页并将它们存储在传递给视图的变量中:
Get posts, order them, paginate them, and store them in a variable that you pass to your view:
public function show()
{
$posts = Post::orderBy('date','desc')->paginate(5);
return view('welcome', compact('posts'));
}
或者获取帖子,对其进行排序并在将其传递到视图时对其进行分页:
Or get the posts, order them and paginate them while passing them to the view:
public function show()
{
return view('welcome',[ 'posts' => Post::orderBy('date','desc')->paginate(5) ]);
}
这篇关于Laravel订单使用分页器时日期不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!