在 laravel 中反转 contains()?
Reverse contains() in laravel?
我是 laravel 的新手,
我试图根据 table 与另一个 table.
的多对多关系从中获取一行
你知道当你在 contain()
中传递多个 id 来检查它们是否与该行有关系时,就像这样:
$row->contains([4,6,9]);
我想扭转这一局面,我可以使用 ID [4,6,9]
从与它们链接的其他 table 获取任何行。
假设您有这两个模型:User
和 Role
建立了 many-to-many 关系。
如果你正确地定义了你的关系:
/** User.php */
public function roles()
{
return $this->belongsToMany(Role::class);
}
-
/** Role.php */
public function users()
{
return $this->belongsToMany(User::class);
}
然后你就可以使用关系来完成你想要做的事情了。
来自相关对象:
$user = User::find(1);
// getting all the roles attached with a user:
$roles = $user->roles;
// getting all the roles attached with a user that has certain ids:
$roles = $user->roles()->whereIn('id', [2, 4, 6])->get();
此外,您可以使用 return 关系的集合实例找到所需的相关模型:
$user = User::find(1);
// getting all the roles attached with a user:
$roles = $user->roles;
// getting a specific role attached to a user:
$specific_role = $roles->where('id', 6)->first();
我是 laravel 的新手, 我试图根据 table 与另一个 table.
的多对多关系从中获取一行你知道当你在 contain()
中传递多个 id 来检查它们是否与该行有关系时,就像这样:
$row->contains([4,6,9]);
我想扭转这一局面,我可以使用 ID [4,6,9]
从与它们链接的其他 table 获取任何行。
假设您有这两个模型:User
和 Role
建立了 many-to-many 关系。
如果你正确地定义了你的关系:
/** User.php */
public function roles()
{
return $this->belongsToMany(Role::class);
}
-
/** Role.php */
public function users()
{
return $this->belongsToMany(User::class);
}
然后你就可以使用关系来完成你想要做的事情了。
来自相关对象:
$user = User::find(1);
// getting all the roles attached with a user:
$roles = $user->roles;
// getting all the roles attached with a user that has certain ids:
$roles = $user->roles()->whereIn('id', [2, 4, 6])->get();
此外,您可以使用 return 关系的集合实例找到所需的相关模型:
$user = User::find(1);
// getting all the roles attached with a user:
$roles = $user->roles;
// getting a specific role attached to a user:
$specific_role = $roles->where('id', 6)->first();