简体   繁体   English

在 Laravel 8 中按类别显示帖子

[英]Display Posts by Category in Laravel 8

i have some issues that happen with my code for displaying posts by category.. Relation is one to many, post to category.. I can route to choosen category, but posts did not show..我的代码按类别显示帖子时出现了一些问题。关系是一对多,帖子到类别。我可以路由到选择的类别,但帖子没有显示。

Here's my Post Model:这是我的帖子模型:

public function category()
    {
        return $this->belongsTo(CategoriesPost::class);
    }

Category Model:类别型号:

public function posts()
    {
        return $this->hasMany(Post::class, 'category_id');
    }

And here's my PostController这是我的 PostController

$posts = Post::where('article_status', 'published')->whereHas('category', function ($query) use ($slug) {
            return $query->where('category_slug', $slug);
        });

$category = CategoriesPost::where('category_slug', $slug)->first();

return view('pages.article', [
            'posts' => $posts,
            'category' => $category,
        ]);

I'm so sure my code was right, but why it didn't shows the posts, did anyone notice where's the problem of my code?我很确定我的代码是正确的,但是为什么它没有显示帖子,有没有人注意到我的代码的问题在哪里?

Rather than querying for the related Posts separately, why not access them via the relationship you have defined in your Category model?与其单独查询相关的Posts ,为什么不通过您在Category模型中定义的关系来访问它们? It will improve performance by reducing the number of calls to your database for a start.它将通过减少对数据库的调用次数来提高性能。

So something like:所以像:

$category = CategoriesPost::with(['posts'])->where('category_slug', $slug)->first();

Then you can just access your posts relationship on the $category property in your view:然后,您可以在视图中访问$category属性上的posts关系:

$category->posts;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM