【发布时间】:2022-03-27 03:02:45
【问题描述】:
我有一些这样的表:
users、followers_pivot、activities
在我的User 模型中,所有关系都已设置并正常工作。
我的 User.php 模型中的一些方法:
class User extends Eloquent {
//The ones I follow
public function imFollowing() {
return $this->belongsToMany('User', 'followers_pivot', 'follower_id', 'followee_id');
}
//The people who's following me
public function followers() {
return $this->belongsToMany('User', 'followers_pivot', 'followee_id', 'follower_id');
}
//shows all activities of the user
public function activities() {
return $this->hasMany('Activity', 'userID');
}
}
我想获取我关注的每个人的活动。
我可以这样获取:
User::with('imFollowing.activities')->find(11);
但是,这还不够。它们在imFollowing 集合下,并由每个用户分隔。
我想直接获取活动,而不是在imFollowings 下分隔。
我想到了“有很多”的关系,但我无法把它放在一起。
这是我尝试使用hasManyThrough:
//User.php Model
public function activityFeed() {
return $this->hasManyThrough('Activity', 'User', 'id', 'userID');
}
和
//in a route
return User::with('activityFeed')->find(11);
但这会返回集合null。
编辑:我可以使用 Fluent 方式来做到这一点:
Activity::join('users', 'activities.userID', '=', 'users.id', 'inner')
->join('followers_pivot', 'followers_pivot.followee_id', '=', 'users.id', 'inner')
->where('followers_pivot.follower_id', 11)
->orderBy('activities.id', 'desc')
->select('activities.*')
->get();
如何使用 Eloquent 实现这一目标?这将是我将使用 Fluent 的唯一地方,我对此不太满意。多态方法对此是否更好?如果有,怎么做?
提前致谢,
【问题讨论】:
-
Eloquent没有提供任何关系,但这会帮助你stackoverflow.com/questions/23788844/… 如果你有什么不清楚的地方问一下 -
@deczo 谢谢,您在该答案中的方法非常棒!尽管它在某种程度上仍然使用 Fluent,但至少比 Fluent 查询要干净得多。
-
你知道,
Eloquent到底是流利的。Eloquent\Builder使用基础Query\Builder。我唯一会更改您在该答案中可以找到的内容是使用 getter 而不是硬编码表名等。您可以依赖$this->relation()->getTable()和此类方法。 -
@deczo 是的,我知道,但问题是我不想在模型中使用表名,除了
protected $table = 'table_name'; -
我明白了,然后按照我之前评论中的建议进行操作:)
标签: php laravel laravel-4 eloquent relationship