[英]Laravel querying multiple related models
例如:我的应用程序中有这些模型。 User
、 Profile
、 Interest
。
我链接的users
与表profiles
通过添加表user_id
列profiles
表。 我通过使用数据透视表 ( interest_profile
) 链接profiles
和interests
,它(很明显)将有两列( profile_id
, interest_id
)。
但是,我想查询与个人资料相关联的用户,也想查看谁与特定兴趣相关联,换句话说:“选择(在他们的个人资料中)具有特定兴趣的所有用户”。
我知道我可以通过加入四个表然后使用 (where 子句) 来使用原始 SQL 来做到这一点。但我想用 Laravel 的方式来做到这一点。
提前致谢。
首先确保您在模型上正确设置了关系,例如:
class User extends Model
{
public function profile()
{
return $this->hasOne(Profile::class);
}
}
class Profile extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
public function interests()
{
return $this->belongsToMany(Interest::class, 'interest_profile');
}
}
class Interest extends Model
{
public function profiles()
{
return $this->belongsToMany(Profile::class, 'interest_profile');
}
}
然后,您可以使用whereHas()
通过相关模型和嵌套关系的点表示法来约束查询。 所以你的查询是:
User::whereHas('profile.interests', function($query) use ($interestName) {
return $query->where('name', $interestName);
})->get();
那只会返回一组用户。 如果您还想返回他们的个人资料和兴趣,您可以使用with()
:
User::whereHas('profile.interests', function($query) use ($interestName) {
return $query->where('name', $interestName);
})
->with('profile.interests')
->get();
假设User
模型有一个关系profile
并且Profile
模型有一个关系interests
,您可以这样做。
$interest_id = 1;
$users = User::whereHas('profile', function ($query) use ($interest_id) {
$query->whereHas('interests', function ($query) use ($interest_id) {
$query->where('id', $interest_id);
});
})->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.