如何在单个类别页面上对帖子进行分页?
public function show($slug) {
$category = Category::where('slug', $slug)->where('online', true)->with(['posts' => function ($q) {
$q->orderBy('id', 'desc');
//I need this query be paginate
}])->first();
//return....
}
my blade loop
<h1>{{$category->name}}</h1>
@foreach($category->posts as $post)
//post data here
@endforeach
答案 0 :(得分:1)
类别和帖子的关系为n:n;
因为只需要一个类别,所以只需要按一个类别获取帖子即可。
尝试使用另一种方法:
MainWindow
在您的刀片循环中:
public function show($slug) {
$cat = Category::where('slug', $slug)
->where('online', true)
->first();
$posts = Post::join('category_posts', 'category_posts.post_id', '=', 'posts.id')
->where('category_posts.category_id', $cat->id)
->selectRaw('posts.*')
->paginate(10);
//return....
}
答案 1 :(得分:0)
这是我在几个项目中经常使用的确切示例。
控制器:
<h1>{{$cat->name}}</h1>
@foreach($posts as $post)
//post data here
@endforeach
查看:
public function index(Request $request){
$parts = BikeParts::paginate(5); //you can change how many you want
return view('admin.bike_parts.index_excel', compact(['bike_parts']))->with('i', ($request->input('page', 1) - 1) * 5); // put exact number you are paginating , in here I used 5.
}
答案 2 :(得分:0)
使用first()
代替使用paginate(count)
根据您的代码,这是一个示例,
public function show($slug) {
$category = Category::where('slug', $slug)
->where('online', true)
->with(['posts' => function ($q) {
$q->orderBy('id', 'desc');
}])->paginate(10);
//return....
}
答案 3 :(得分:0)
$ posts = Post :: where('category_id',$ categoryId)-> paginate(10);
答案 4 :(得分:0)
这里有一种方法可以用来获取多个类别的分页帖子
但是,我怀疑这将进行N + 1查询。可能需要为此急切加载。有人可以确认吗?
exp system/manager full=y file="""D:\DB Backup\sys_12c_%fullstamp%.dmp""" log="""D:\DB Backup\sys_12c_%fullstamp%.log"""
在刀片文件中
// Category.php (Model)
public function posts()
{
return $this->hasMany('App\posts', 'post_id', 'id');
}