无法让 Eloquent 的 hasManyThrough 为基本示例工作

Can't get Eloquent's hasManyThrough to work for a basic example

这是我的关系:

User

Collection

UserCollection

我怎样才能得到属于用户的 $user->collections 到 return 所有 Collection objects 的东西? UserCollection 只是将 User 链接到 Collection。这允许一个用户拥有多个collection,也允许一个collection属于多个用户。

我目前正在尝试的是指定 UserCollection 属于 user_id 上的 User,并且属于 collection_id 上的 Collection .

// UserCollection

public function user()
{
    return $this->belongsTo(User::class, 'user_id');
}

public function collection()
{
    return $this->belongsTo(Collection::class, 'collection_id');
}

然后指定一个User有很多CollectionsUserCollection

// User

public function collections()
{
    return $this->hasManyThrough(Collection::class, UserCollection::class);
}

我也试过显式设置 hasManyThrough 关系的列名,但连接尝试使用 UserCollection 模型上的 id 列,该列不存在因为没有主键:

public function collections()
{
    return $this->hasManyThrough(Collection::class, UserCollection::class, 'user_id', 'collection_id');
}

你把这里的事情复杂化了。你不需要 hasManyThrough。您需要的是 belongsToMany() 多对多关系。

首先,摆脱你的 UserCollection 模型。你不需要它。

然后把你的关系改成这样:

public function collections(){
    return $this->belongsToMany('Collection', 'user_collections');
}

public function users(){
    return $this->belongsToMany('User', 'user_collections');
}

有关详细信息,请查看 official docs on relations