【问题标题】:Laravel Get 'belongsTo' relation from 'hasMany' relationLaravel 从“hasMany”关系中获取“belongsTo”关系
【发布时间】:2015-11-29 22:33:55
【问题描述】:
class Post {
    function category() {
        $this->belongsTo('Category');
    }
}
class User {
    function posts() {
        $this->hasMany('Post');
    }

    function categories() {
        //???
        $this->posts->category;
    }
}

我的代码看起来像这样,我想知道如何访问用户对象上的“类别”并让它返回 Laravel 关系。

现有的关系方法“hasManyThrough”等似乎都不适合这个用例。

【问题讨论】:

    标签: php laravel laravel-4 laravel-5 relationship


    【解决方案1】:

    另一种解决方案:

    //user model
    public function getCategoriesAttribute()
    {
        return $this->posts->lists('category')->unique();
    }
    

    要限制查询,您可以更改帖子关系

    //user model
    function posts() {
        $this->hasMany('Post')->with('category');
    }
    

    来源:http://softonsofa.com/laravel-querying-any-level-far-relations-with-simple-trick/

    【讨论】:

      【解决方案2】:

      也许你可以换个角度看?从类别开始并按用户过滤:

      $userCategories = Category::whereHas('posts' function($query){
          $query->where('user_id', $userId);
      })->get();
      

      这将抓取用户发帖的所有类别。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-12-22
        • 1970-01-01
        • 2019-07-26
        • 1970-01-01
        • 2014-10-29
        • 2017-06-08
        • 1970-01-01
        相关资源
        最近更新 更多