簡體   English   中英

laravel 如何對單個類別的帖子進行分頁

[英]laravel how to paginate single category posts

如何在單個類別頁面中對帖子進行分頁?

代碼

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

類別和帖子的關系是n:n;

因為您只需要一個類別,所以您只需要按一個類別獲取帖子。

嘗試使用另一種方法:

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....
}

在你的刀片循環中:

<h1>{{$cat->name}}</h1>

@foreach($posts as $post)
  //post data here
@endforeach

這是我在幾個項目中經常使用的確切示例。

Controller:

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.
}

看法:

  <table class="table table-actions-bar m-b-0">
  <tbody>
 <thead>
       <tr>
        <th>id</th>
         <th>PartNo.</th>
         <th>Part Name</th>
         <th>model</th>
         <th>Retail Price</th>
         </tr>
</thead>
 @foreach($bike_parts as $bike_part)
    <tr>
        <td><a href="#,{{$bike_part->id}}">{{$loop->index+1}}</a></td>
        <td>{{$bike_part->part_number}}</td>
        <td>{{$bike_part->description}}</td>
        <td>{{$bike_part->bike_model}}</td>
        <td>{{$bike_part->retail_price}}</td>
    </tr>
 @endforeach
</tbody>
</table>
{!! $bike_parts->render() !!}

不要使用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.... 
}

$posts = Post::where('category_id', $categoryId)->paginate(10);

這是一種可用於實現類別分頁帖子的方法

但是,我懷疑這會進行 N+1 查詢。 可能需要用這個實現急切加載。 有人可以證實這一點嗎?

// Category.php (Model)
public function posts()
{
    return $this->hasMany('App\posts', 'post_id', 'id');
}

在刀片文件中

@foreach($categories as $category)
    <h1>{{$category->name}}</h1>

    @foreach($category->posts()->paginate() as $post)
        //post data here
    @endforeach
@endforeach

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM