[英]Sending posts with a specific category to the view in Laravel
I am making a blog in Laravel Framework.我正在 Laravel 框架中创建一个博客。 I want to send posts to the frontend view that have a specific category.
我想将帖子发送到具有特定类别的前端视图。 How can i do this when i have a separate category table that is connected to the posts table?
当我有一个单独的类别表连接到帖子表时,我该怎么做? For example, my posts table has a category_id that is connected to the category table.
例如,我的帖子表有一个 category_id 连接到类别表。
Post model:岗位型号:
public function category(){
return $this->belongsTo('App\Category');
}
Category model:类别型号:
public function posts(){
return $this->hasMany('App\Post');
}
Now, how can i send posts to the view, but only posts that have a specific category, for example "Archive"?现在,我如何将帖子发送到视图,但只能发送具有特定类别的帖子,例如“存档”?
I know it should be something like:我知道它应该是这样的:
public function index()
{
$rows = Post::notdeleted()->get();
return view('admin.posts.index', compact('rows'));
}
but i dont know how to get the category since it is a category_id 1 in posts table and "archive" in category table.但我不知道如何获取类别,因为它是帖子表中的 category_id 1 和类别表中的“存档”。
I think you want to filter the post by category name.我认为您想按类别名称过滤帖子。
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'));
}
You can do something like this:你可以这样做:
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.