Laravel Get 'belongsTo' relation from 'hasMany&#


Laravel Get 'belongsTo' relation from 'hasMany' relation

class Post {
    function category() {
        $this->belongsTo('Category');
    }
}
class User {
    function posts() {
        $this->hasMany('Post');
    }
    function categories() {
        //???
        $this->posts->category;
    }
}

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

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

也许你可以从另一个角度看这件事?从类别和按用户筛选开始:

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

这将获取用户发布到的所有类别。

另一个解决方案:

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

要限制查询,可以更改post关系

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

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