Laravel中如何获取用户关注或订阅的所有不重复Profile?
获取用户订阅/关注的所有不重复Profile
下面提供两种实用方案,可根据数据量和需求选择:
方案一:集合层面合并去重(适合数据量较小场景)
直接利用Laravel集合的merge和unique方法,把两个关联结果合并后去重。在User模型里新增方法封装逻辑:
public function allInterestedProfiles() { // 合并订阅、关注的Profile集合,按ID去重 return $this->subscribeProfiles->merge($this->followProfiles)->unique('id'); }
使用时调用$user->allInterestedProfiles()就能得到去重后的Profile集合。这种写法简单直观,但会先把两个关联的所有数据加载到内存再处理,数据量大时可能影响性能。
方案二:数据库层面联合查询(适合数据量较大场景)
在数据库层通过union或distinct实现去重,减少内存占用,性能更优。在User模型里封装方法:
方式1:利用Union查询
public function allInterestedProfiles() { // 获取订阅、关注的查询构造器实例 $subscribedQuery = $this->subscribeProfiles()->getQuery(); $followedQuery = $this->followProfiles()->getQuery(); // 通过Union合并两个查询并返回结果 return Profile::fromSubquery($subscribedQuery->union($followedQuery)); }
方式2:用WhereIn + Distinct
public function allInterestedProfiles() { return Profile::whereIn('id', function($query) { // 筛选当前用户订阅的Profile ID $query->select('profile_id') ->from('subscribers') ->where('id', $this->id); })->orWhereIn('id', function($query) { // 筛选当前用户关注的Profile ID $query->select('profile_id') ->from('followers') ->where('id', $this->id); })->distinct(); // 去重 }
后续扩展
如果之后新增更多关联(比如收藏Profile),方案一只需要在merge里加入新的关联集合(如->merge($this->favoriteProfiles));方案二则需要在查询中添加对应的Union分支或WhereIn条件即可。
内容的提问来源于stack exchange,提问作者wtsuport
相关产品推荐
相关产品推荐

