当表中不存在直接引用时在 Laravel 中定义 HasManyThrough 关系

问题描述 投票:0回答:2

我目前正在使用 Laravel 11 并具有以下数据库结构:

  • users

    • id
  • artworks

    • id
  • collections

    • id
  • collection_user

    • id
    • 集合_id
    • 用户ID
  • artwork_collection

    • id
    • artwork_id
    • 集合_id

在此设置中,一个用户可以拥有多个收藏,一个收藏可以属于多个用户,一件艺术品可以属于多个收藏。我相信我已经正确设置了结构和模型:

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 eloquent laravel-relations laravel-11
2个回答
0
投票

您需要的关系类型不是多对多吗?

有关此类关系,请参阅 Eloquent 文档。有模型应具有的结构示例。

Laravel 文档


0
投票

经过一番摆弄(以及人工智能的帮助),我想出了这个。我不知道这是否是最佳实践,并且很想知道 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();
}
© www.soinside.com 2019 - 2024. All rights reserved.