我目前正在使用 Laravel 11 并具有以下数据库结构:
users
artworks
collections
collection_user
artwork_collection
在此设置中,一个用户可以拥有多个收藏,一个收藏可以属于多个用户,一件艺术品可以属于多个收藏。我相信我已经正确设置了结构和模型:
class Artwork extends Model
{
public function collections(): BelongsToMany
{
return $this->belongsToMany(Collection::class)->withTimestamps();
}
}
class Collection extends Model
{
public function artworks(): BelongsToMany
{
return $this->belongsToMany(Artwork::class)->withTimestamps();
}
public function users(): BelongsToMany
{
return $this->belongsToMany(User::class)->withTimestamps();
}
}
class User extends Authenticatable
{
public function collections(): BelongsToMany
{
return $this->belongsToMany(Collection::class)->withTimestamps();
}
}
我的问题是:我应该如何在用户模型中定义
artworks()
关系函数来检索用户通过集合拥有的所有艺术品?
我尝试使用
hasManyThrough
关系,但似乎需要在 artworks
和 collections
表之间直接引用 users
。
public function artworks(): HasManyThrough
{
return $this->hasManyThrough(Artwork::class, Collection::class);
}
我应该引入枢轴模型吗?或者也许我需要执行连接操作?
经过一番摆弄(以及人工智能的帮助),我想出了这个。我不知道这是否是最佳实践,并且很想知道 Laravel 的实际方法(如果还不是):
public function artworks()
{
return $this->belongsToMany(Artwork::class, 'collection_user', 'user_id', 'collection_id')
->join('artwork_collection AS ac', 'collection_user.collection_id', '=', 'ac.collection_id')
->join('artworks AS aw', 'ac.artwork_id', '=', 'aw.id')
->distinct()
->withTimestamps();
}