【问题标题】:Relationship between user and store用户与商店的关系
【发布时间】:2020-12-10 13:50:58
【问题描述】:

我需要在用户和许多商店之间建立关系。我已经创建了三个模型

Store Model

id name email            phone       info
1  xyz  xyz@gmail.com    9329292922  Small Store
2  abc  abc@gmail.com    9494949449  Some Store

User Model

id name email                  
1  ewd  ewd@gmail.com   
2  xcv  xcv@gmail.com    

User_Store

user_id     store_id
   1          1
   1          2

user_store模型是belongstoMany还是hasmany包含什么关系?

【问题讨论】:

    标签: laravel-5 eloquent relationship php-7.1


    【解决方案1】:

    你可以使用belongsToMany关系

    在你的 Store 模型中定义一个方法

       public function users() {
                return $this->belongsToMany(Users::class, 'user_store', 'user_id', 'store_id');
            }
    

    在你的用户模型中定义一个方法

     public function stores() {
        return $this->belongsToMany(Stores::class, 'user_store', 'user_id', 'store_id');
    }
    

    【讨论】:

    【解决方案2】:

    在我看来你想要一个简单的many-to-many 关系。

    为此,您只需要两个模型UserStore,如果您想对数据透视表做一些特殊的事情,则只需要StoreUser,否则就没有必要了。

    以下是 Laravel 的方式:

    表结构

    stores
        id
        name
        email
        phone 
        info
    
    users
        id
        name
        email  
    
    store_user
        user_id
        store_id
    

    Laravel 的数据透视表除外,它被称为 store_user,您可以阅读更多关于它的信息 here

    要定义这种关系,需要三个数据库表:usersrolesrole_userrole_user 表派生自 相关型号名称的字母顺序,并包含 user_idrole_id 列。

    模型结构

    class User extends Model
    {
        public function stores()
        {
            return $this->belongsToMany(Store::class);
        }
    }
    
    
    class Store extends Model
    {
        public function users()
        {
            return $this->belongsToMany(User::class);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-12-30
      • 2021-04-23
      • 1970-01-01
      • 1970-01-01
      • 2012-07-17
      • 1970-01-01
      • 2020-10-25
      • 2016-09-11
      • 2016-09-24
      相关资源
      最近更新 更多