【问题标题】:How do I take related posts (by category) with Eloquent?如何使用 Eloquent 获取相关帖子(按类别)?
【发布时间】:2018-12-13 03:33:27
【问题描述】:

我有一个关于如何使用 Eloquent 按类别获取特定帖子的相关帖子的问题。我知道如何在纯 MySQL 中做到这一点,但我相信 Eloquent 会有更好的替代方案。

我的表格是:帖子类别 post_category (pivot)

我已经建立了必要的 Eloquent 连接,所以我想做这样的事情:$post->categories()->posts()->exclude($post)->get()

这当然行不通。我在posts() 上收到错误,因为“Builder 没有方法posts()”,但希望你能明白。你会如何使用 Eloquent?

【问题讨论】:

  • 它可能类似于Category::whereIn($post->categories->lists('id'))->posts()->get()
  • 是的,这样的事情可以工作,但它给了我一个错误Call to undefined method Illuminate\Database\Query\Builder::posts()

标签: php laravel eloquent


【解决方案1】:

很难说你想达到什么,bot可能你想得到:

Posts::whereIn('id', $post->categories()->lists('id'))->whereNot('id',$post->id)->get();

【讨论】:

    【解决方案2】:

    关于 Eloquent 关系的一个令人困惑的部分是,模型上定义关系的方法会在调用时带回一个关系对象,就像你正在调用它一样:

    $posts->categories();
    

    要返回附加到您的帖子的类别模型集合,您应该使用以下内容:

    Post::find(primary key of post)->categories;
    

    或者获取所有帖子并单独遍历模型:

    $posts = Post::all();
    
    foreach($posts as $post) {
        $post->categories;
    }
    

    这是我发现对学习使用 Eloquent 的关系方法很有帮助的资源:@​​987654321@

    【讨论】:

    • 我无法在收藏中调用->categories。这种方式似乎行不通。
    • 你是对的。您需要一个帖子模型才能使用。请参阅我的修改以进行更正。
    【解决方案3】:

    我试图按类别获取我的相关帖子并在谷歌上搜索并到达这里。 我做了这个,效果很好。

       public function getSingle($slug){
            $post = Post::where('slug', '=', $slug)->first();
            $tags=Tag::all();
            $categories=Category::all();
    
            $related= Post::where('category_id', '=', $post->category->id)
                ->where('id', '!=', $post->id)
                ->get();
    
            return view('blog.show')
                ->withPost($post)
                ->withTags($tags)
                ->withCategories($categories)
                ->withRelated($related);         
        }
    

    在我的视图中('blog.show')

    $post->title
    $post->content
    
    //related posts
    @foreach($related as $posts)
      $posts->title
      $posts->category->name
    @endforeach
    

    我不知道这是否正确,但它对我有用。我希望这可以帮助某人

    【讨论】:

      【解决方案4】:

      为什么不定义一个“relatedposts”关系来搜索具有相同类别 ID 的帖子? 然后你可以简单地做$post->relatedposts...

      imo 太复杂了……

      【讨论】:

        猜你喜欢
        • 2023-02-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多