Php 将具有特定类别的帖子发送到Laravel中的视图
我正在用Laravel框架写博客。我想向前端视图发送具有特定类别的帖子。当我有一个单独的类别表连接到posts表时,我该怎么做? 例如,“我的帖子”表有一个连接到该类别表的类别id 后模型:Php 将具有特定类别的帖子发送到Laravel中的视图,php,mysql,laravel,Php,Mysql,Laravel,我正在用Laravel框架写博客。我想向前端视图发送具有特定类别的帖子。当我有一个单独的类别表连接到posts表时,我该怎么做? 例如,“我的帖子”表有一个连接到该类别表的类别id 后模型: public function category(){ return $this->belongsTo('App\Category'); } 类别模型: public function posts(){ return $this->hasMany('App\Post');
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'));
}
但我不知道如何获取该类别,因为它是posts表中的category\u id 1和category表中的“archive”。您可以这样做:
public function index()
{
$rows = Post::whereHas('category',function($q){
$q->where('category_name','archive');
})->get();
return view('admin.posts.index', compact('rows'));
}
我想你应该按类别名称筛选帖子
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'));
}