繁体   English   中英

Laravel 查询多个相关模型

[英]Laravel querying multiple related models

例如:我的应用程序中有这些模型。 UserProfileInterest

我链接的users与表profiles通过添加表user_idprofiles表。 我通过使用数据透视表 ( interest_profile ) 链接profilesinterests ,它(很明显)将有两列( profile_idinterest_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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM