[英]Getting specific category posts with appserviceprovider in laravel
[英]Sending posts with a specific category to the view in Laravel
我正在 Laravel 框架中創建一個博客。 我想將帖子發送到具有特定類別的前端視圖。 當我有一個單獨的類別表連接到帖子表時,我該怎么做? 例如,我的帖子表有一個 category_id 連接到類別表。
崗位型號:
public function category(){
return $this->belongsTo('App\Category');
}
類別型號:
public function posts(){
return $this->hasMany('App\Post');
}
現在,我如何將帖子發送到視圖,但只能發送具有特定類別的帖子,例如“存檔”?
我知道它應該是這樣的:
public function index()
{
$rows = Post::notdeleted()->get();
return view('admin.posts.index', compact('rows'));
}
但我不知道如何獲取類別,因為它是帖子表中的 category_id 1 和類別表中的“存檔”。
我認為您想按類別名稱過濾帖子。
public function index(){
// For example Archive
$categoryName= request()->get('category_name');
$posts = Post::whereHas('category',function($query) use ($categoryName){
$query->where('name','like',"%{$categoryName}%");
});
return view('admin.posts.index', compact('posts'));
}
你可以這樣做:
public function index()
{
$rows = Post::whereHas('category',function($q){
$q->where('category_name','archive');
})->get();
return view('admin.posts.index', compact('rows'));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.