应该是怎样的关系?
What kind of relationship should be?
我有两个模型:Users
和 Categories
。
我需要获取用户订阅的所有类别。
做,数据库结构为:
User Category UserCategory
___ _________ __________
id id | name category_id user_id
类别模型是:
public function user()
{
return $this->belongsToMany('App\User', 'user_id', 'id');
}
用户模型为:
public function categories()
{
return $this->belongsToMany('App\Category');
}
我试图获取用户通过第三次订阅的所有类别table:
$categories = Category::with("user")->where("id", Auth::user()->id)->get();
它对我不起作用
要获取属于用户的所有类别,请使用 whereHas()
方法:
$categories = Category::whereHas('users', function($q) use($userId) {
$q->where('id', $userId);
})->get();
此外,确保 table 名称为 categories_users
并定义 users
关系,如下所示:
public function users()
{
return $this->belongsToMany('App\User');
}
我有两个模型:Users
和 Categories
。
我需要获取用户订阅的所有类别。
做,数据库结构为:
User Category UserCategory
___ _________ __________
id id | name category_id user_id
类别模型是:
public function user()
{
return $this->belongsToMany('App\User', 'user_id', 'id');
}
用户模型为:
public function categories()
{
return $this->belongsToMany('App\Category');
}
我试图获取用户通过第三次订阅的所有类别table:
$categories = Category::with("user")->where("id", Auth::user()->id)->get();
它对我不起作用
要获取属于用户的所有类别,请使用 whereHas()
方法:
$categories = Category::whereHas('users', function($q) use($userId) {
$q->where('id', $userId);
})->get();
此外,确保 table 名称为 categories_users
并定义 users
关系,如下所示:
public function users()
{
return $this->belongsToMany('App\User');
}