0 レビュー
2 回答
php-laravelのリレーションテーブルのデータに従ってpaginateを表示します
Laravelでブログを作成します。ブログに投稿フォームのカテゴリが表示され、投稿ごとにのみpaginateを表示できますが、カテゴリIDと関係のある投稿に対してのみpaginateを表示したいと思います
コードに問題があります。問題の修正を手伝ってください。
コントローラーのソースコード:
//this code show posts according to category id
$postCatId = $request->postCatId;
$postList =PostCat::with("posts")->where('id',$postCatId)->get();
//this code show paginate according to posts has relation with category
$paginate=PostCat::with("posts")->where('id',$postCatId)->paginate(2);
これにより、表示する $postList
と$paginate
が返されます
表示中:
//showpostsはカテゴリIDと関係があります
@foreach($ PostList as $ post)
@foreach($ post-> post as $ post_item)
{{$ post_item-> id}}
@endforeach
@endforeach
//投稿に応じてpaginateを表示しますカテゴリIDと関係があります
{{$paginate->links()}}
ただし、カテゴリIDに関連する投稿でpaginateを表示することはできません
わからない
0
レビュー
答え :
解決策:
カテゴリのある投稿をページ分割する場合は、現在の2つのクエリの代わりに次のクエリを使用してください:
$posts = Post::with('category')
->has('category')
->where('id', $postCatId)
->paginate(2);
Post
モデルにcategory()
の関係があることを確認してください。
public function category()
{{
$ this-> belongsTo('App \ Post Cat');を返します。
}
ビューで$posts
を繰り返し、リンクをレンダリングします:
@foreach($posts as $ post)
PostIDは{{$post->id}}で、カテゴリIDは{{$ post-> category-> id}}
@endforeach
{{$ paginate-> render()}}
答えへのリンク
わからない
0
レビュー
答え :
解決策:
Laravel 5で多対多の関係を築き、これをページ化するためのより簡単な方法:
カテゴリモデル:
public function articles()
{
return $this->belongsToMany('App\Article');
}
記事モデル:
public function categories()
{
return $this->belongsToMany('App\Category');
}
ページネーションのあるカテゴリからすべての投稿/記事をダウンロードする場合:
$category = Category::where('slug', $slug)->firstOrFail();
$category_articles = $category->articles()->orderBy('created_at', 'desc')->paginate(10);
わからない
同様の質問
私たちのウェブサイトで同様の質問で答えを見つけてください。