首页 文章

Laravel多对多的多态关系

提问于
浏览
0

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

我有 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_isuserable_type 并添加这个额外的 userables 表吗?

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

1 回答

  • 0

    在多对多的多态关系中,你应该有userables表和users表 . 和 userable_iduserable_type 应该在userables表中,而不是在users表中 .

    userables table:

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

    Business, School and Council Model:

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

    User Model

    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);
    }
    

    请参阅doc中的Many to many polymorphic relation .

相关问题