【问题标题】:Laravel Many To Many Polymorphic RelationsLaravel 多对多多态关系
【发布时间】:2017-02-28 21:22:38
【问题描述】:

我有一个关于如何定义以下关系的快速问题

我有一个USER,它可以属于许多Councils、许多Schools 和许多Businesses。

现在我知道我可以为上述所有内容创建一个数据透视表,例如

council_user
school_user
business_user

这意味着我可以从数据库中提取所有 councils 和 user 所属的所有 businesses 等

为了节省我这样做,有一个更好的方法,有 3 个pivot tables,我可以使用多对多多态关系并这样做吗,如果有的话,有人知道它看起来像一个表结构吗?

我觉得应该是……

business
id - integer
name - string

council
id - integer
name - string

school
id - integer
name - string

userables
user_id - integer
userable_id - integer
userable_type - string

如果是这样,我是否要从我的 USER 表中删除 userable_is 和 userable_type 并拥有这个额外的 userables 表?

有谁知道这是如何工作的,我完全误解了多态关系的作用吗?

【问题讨论】:

    标签: laravel eloquent polymorphism relationships


    【解决方案1】:

    在多对多多态关系中,您应该有 userables 表和 users 表。 userable_id 和 userable_type 应该在 userables 表中,而不是在 users 表中。

    用户表:

    user_id   userable_id  userable_type
    1         1             App\Business
    1         2             App\School
    ...
    

    企业、学校和议会模式:

    public function users()
    {
        return $this->morphToMany('App\User', 'userable');
    }
    

    用户模型:

    public function businesses()
    {
          return $this->morphedByMany('App\User', 'userable');
    }
    
    public function schools()
    {
          return $this->morphedByMany('App\User', 'userable');
    }
    
    public function councils()
    {
          return $this->morphedByMany('App\User', 'userable');
    }
    

    那么,这就给出了user_id为1的用户的所有业务。

    $users=User::find(1);
    foreach($user->businesses as $business)
    {
       print_r($business->name);
    }
    

    请参阅文档中的Many to many polymorphic relation。

    【讨论】:

      猜你喜欢
      • 2016-01-26
      • 1970-01-01
      • 2015-09-14
      • 2020-12-15
      • 1970-01-01
      • 1970-01-01
      • 2018-06-15
      • 2019-02-07
      • 2018-01-22
      相关资源
      最近更新 更多