如何区分所有类别的用户?

How to gell all categories of user?

我有两个模型:UserCategory

每个用户可以在 table User_categories 中拥有一个或多个类别。

还有tableUserCategories.

我的关系是:

用户

public function categories(){
    return $this->hasMany('App\Category');
}

类别

public function users(){
    return $this->belongsToMany('App\User');
}

我尝试通过模型获取所有类别的用户 Category:

User::where("id", $id)->with("country", "city", "categories")->first();

结果:

我尝试获取类别名称:

@foreach($profile->categoriesPivot() as $item)
<span class="label label-default">{{$item->category()->name}}</span>
 @endforeach

由于您在这里尝试使用多对多,请将关系更改为:

public function categories()
{
    return $this->belongsToMany('App\Category');
}

枢轴 table 名称应为 category_user

这个案例定义为一对多

在您的 User 模型中定义

public function getAllCategoriesAttribute()
{
    return Category::where('user_id', $this->id)->get();
}

然后在您的控制器中尝试

$user = User::find($user_id);
dd($user->allCategories);

已更新:以上一对多情况下的源代码


这种情况定义为多对多

在您的 User 模型中定义

public function categories(){
    return $this->belongsToMany('App\Category', 'category_user', 'user_id', 'category_id');
}

并在您的控制器中

dd($user->categories);

由于您已经在用户模型中设置了关系,正确的做法是:

// Get all categories from user by $id $categories = User::find($id)->categories()->get();