2017-06-02 216 views
0

例如:我在我的应用程序中有这些模型。 UserProfileInterestLaravel查询多个相关模型

我通过添加profiles表中的user_id列链接users表和profiles表。我通过使用数据透视表(interest_profile)链接profilesinterests,这是(很明显)将有两列(profile_id,interest_id)。

但是,我想查询与配置文件关联的用户,也看到谁与特定兴趣相关联,换句话说:“选择所有具有(在他们的配置文件中)特定兴趣的用户”。

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

在此先感谢。

回答

1

首先确保你正确有你的关系建立在你的模型,如:

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

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