当表不提供直接关系信息时如何定义HasManyThrough关系?

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

我正在使用 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);
}

我需要添加枢轴模型吗?我需要加入什么吗?

laravel eloquent laravel-11
1个回答
0
投票

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

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

Laravel 文档

© www.soinside.com 2019 - 2024. All rights reserved.