Laravel从'hasMany'关系获得'belongsTo'关系

时间:2022-10-04 09:56:53
class Post {
    function category() {
        $this->belongsTo('Category');
    }
}
class User {
    function posts() {
        $this->hasMany('Post');
    }

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

I have code that looks like this, and I'm wondering how I can access "categories" on the user object and have it return a Laravel relation.

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

None of the existing relation methods "hasManyThrough", etc seem to fit this use case.

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

2 个解决方案

#1


1  

Perhaps you can look at it the other way? Starting at the categories and filtering by user:

也许你可以用另一种方式看待它?从类别开始并按用户过滤:

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

This will grab all categories where a user has made a post to.

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

#2


0  

An other solution :

另一个解决方案:

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

To limit queries you can change posts relationship

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

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

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

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

#1


1  

Perhaps you can look at it the other way? Starting at the categories and filtering by user:

也许你可以用另一种方式看待它?从类别开始并按用户过滤:

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

This will grab all categories where a user has made a post to.

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

#2


0  

An other solution :

另一个解决方案:

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

To limit queries you can change posts relationship

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

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

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

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