Laravel查询多个相关模型

Laravel querying multiple related models

例如:我的应用程序中有这些模型。 User, Profile, Interest.

我通过在 profiles [=36= 中添加 user_id 列将 users table 与 profiles table 链接起来].我通过使用枢轴 table (interest_profile) 链接了 profilesinterests,这(很明显)将有两列(profile_idinterest_id).

但是,我想查询与配置文件相关联的用户,也想查看与特定兴趣相关联的用户,换句话说:"select all users who are having (in their profiles) that particular interest"。

我知道我可以通过加入四个 table 然后使用(where 子句)来使用原始 SQL 来做到这一点。但是我想用 Laravel方式。

提前致谢。

假设User模型有关系profileProfile模型有关系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();

首先确保您在模型上正确设置了关系,例如:

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();

那只是 return 一组用户。如果你想 return 他们的个人资料和兴趣,你可以使用 with():

User::whereHas('profile.interests', function($query) use ($interestName) {
    return $query->where('name', $interestName);
})
->with('profile.interests')
->get();