简体   繁体   English

用户与店铺的关系

[英]Relationship between user and store

I need to create a relationship between user and many stores.我需要在用户和许多商店之间建立关系。 I have created a three models我创建了三个模型

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

What does the user_store model contain relations whether it is belongstoMany or hasmany? user_store model 包含什么关系,是 belongstoMany 还是 hasmany?

You can use belongsToMany relationship您可以使用 belongsToMany 关系

In your Store model define a method在你的 Store model 定义一个方法

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

In your Users model define a method在您的用户 model 中定义一个方法

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

Looks to me like you want a simple many-to-many relationship.在我看来你想要一个简单的多对多关系。

For this you only need two models User and Store , you only need StoreUser if you want to do something special with the pivot table otherwise it is unnecessary.为此你只需要两个模型UserStore ,如果你想对 pivot 表做一些特殊的事情,你只需要StoreUser否则就没有必要了。

The following would be the Laravel way:以下是 Laravel 方式:

Table structure表结构

stores
    id
    name
    email
    phone 
    info

users
    id
    name
    email  

store_user
    user_id
    store_id

Laravel excepts the pivot table to be called store_user , you can read more about it here : Laravel 除了 pivot 表被称为store_user ,您可以在这里阅读更多相关信息:

To define this relationship, three database tables are needed: users , roles , and role_user .要定义此关系,需要三个数据库表: usersrolesrole_user The role_user table is derived from the alphabetical order of the related model names, and contains the user_id and role_id columns. role_user表是根据相关的 model 名称的字母顺序派生的,包含user_idrole_id列。

Model structure Model结构

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


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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM