简体   繁体   中英

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?

You can use belongsToMany relationship

In your Store model define a method

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

In your Users model define a method

 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.

The following would be the Laravel way:

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 :

To define this relationship, three database tables are needed: users , roles , and role_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.

Model structure

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


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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