laravel 显示2关系的结果

bvjxkvbb  于 2022-11-18  发布在  其他
关注(0)|答案(1)|浏览(115)

在我的应用程序中,用户可以订阅或关注个人资料。因此,我在用户和个人资料之间有2个关系。可能会更大。我如何显示返回所有用户关注或订阅的个人资料(没有重复)?

public function subscribeProfiles()
{
    return $this->belongsToMany(Profile::class, 'subscribers', 'profile_id', 'id');
}

public function followProfiles()
{
    return $this->belongsToMany(Profile::class, 'followers', 'profile_id', 'id');

}
a14dhokn

a14dhokn1#

最简单的方法是将这两种关系合并在一起。

$user->subscribeProfiles
    ->merge($user->followProfiles)
    ->unique('id');

但是,如果您有数千个配置文件并希望分页,那么下面的方法将存在问题。在这种情况下,您可能希望将几个表连接在一起。

Profile::join('subscribers', 'subscribers.profile_id', '=', 'profiles.id')
    ->join('followers', 'followers.profile_id', '=', 'followers.id')
    ->where('subscribers.user_id', $user->id)
    ->orWhere('followers.user_id', $user->id)
    ->distinct()
    ->get();

相关问题