【问题标题】:Eloquent Has Many Through from same tableEloquent 有很多来自同一张桌子
【发布时间】:2022-03-27 03:02:45
【问题描述】:

我有一些这样的表:

usersfollowers_pivotactivities

在我的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


【解决方案1】:

我也有同样的疑问。由于这是第一个谷歌答案,我将在此处发布答案:

正如这里所解释的Has many through self referencing in laravel returns empty set

这不是 HasManyThrough 关系,而是 BelongsToMany 关系!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-23
    • 2017-02-07
    • 2011-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-29
    相关资源
    最近更新 更多