【问题标题】:In Laravel Eloquent can I define a many-to-many relationship without a pivot table?在 Laravel Eloquent 中,我可以在没有数据透视表的情况下定义多对多关系吗?
【发布时间】:2021-06-04 07:31:31
【问题描述】:

我有一个表以多对多的方式链接到多个其他表。

在我的示例中,pmds(主要医生)是users 表中的记录

  1. roles 表中有一个与pmd 对应的role_id;和
  2. 通过中间表site_usersites表关联;或
  3. 通过中间表agency_useragency表关联

User.php下面的函数获取我想要的信息...

    public function allPmds()
    {
        return User::whereHas('role', function ($q) {
            $q->where('name', 'pmd');
        })->where(function ($q) {
            $q->whereHas('siteUsers', function ($q) {
                $q->where('site_id', $this->id);
            })->orWhereHas('agencies', function ($q) {
                $q->where('agency_id', $this->agency_id);
            });
        });
    }

但我真正想要的是渴望加载。像这样的:

public function pmds()
    {
        return $this->belongsToMany('App\User')->where( <essentially the same code as above> );
    }

【问题讨论】:

  • 为什么你需要没有数据透视表的多对多关系?请再解释一下。
  • 我猜你需要很多通过关系,一切都会很棒。

标签: laravel eloquent pivot relational-database


【解决方案1】:

我认为您需要使用多对多多态
docs about many-to-many polymorphic

【讨论】:

    猜你喜欢
    • 2023-02-05
    • 2014-12-07
    • 2013-03-15
    • 2019-10-19
    • 1970-01-01
    • 2020-08-22
    • 2014-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多