我正在使用 Laravel 11 和以下结构:
users
- id
artworks
- id
collections
- id
collection_user
- id
- collection_id
- user_id
artwork_collection
- id
- artwork_id
- collection_id
因此,一个用户可以拥有多个集合,一个集合可以属于多个用户,一件艺术品可以属于多个集合。我希望考虑到这一点,结构和模型设置正确:
<?php
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();
}
}
?>
如何在 User 模型中定义
artworks()
关系函数才能通过 Collections 获取用户拥有的所有艺术品?
我尝试使用 hasManyThrough 关系,但它要求艺术品和收藏表能够直接引用用户。
public function artworks(): HasManyThrough
{
return $this->hasManyThrough(Artwork::class, Collection::class);
}
我需要添加枢轴模型吗?我需要加入什么吗?