Feb 8, 2017
0
Level 9
how to make relation between multiple models (users, shops and roles)
Hi,
I have 3 tables users, shops and roles, each user can create multiple shops and each shop can be managed by multiple users with 2 roles owner(shop creator) and admin.
when a user create a new shop owner role will be assigned and also the same user could be an admin in other shops,
Tables
//Users table:
$table->increments('id');
$table->string('name');
$table->string('email')->unique()->index();
$table->string('password');
$table->rememberToken();
$table->timestamps();
//Shops table:
$table->increments('id');
$table->integer('shop_type_id')->unsigned()->index();
$table->string('name');
$table->string('image');
$table->text('description');
$table->timestamps();
//Roles table:
$table->increments('id');
$table->string('name');
//Role shop table:
$table->integer('role_id')->unsigned()->index();
$table->integer('shop_id')->unsigned()->index();
$table->integer('user_id')->unsigned()->index();
Models:
//User model:
class User extends Authenticatable
{
public function shop()
{
return $this->hasMany(Shop::class);
}
}
//Role model:
class Role extends Model
{
public $timestamps = false;
public function users()
{
return $this->hasMany(User::class);
}
public function shops()
{
return $this->belongsToMany(Shop::class);
}
}
//Shop
class Shop extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
public function roles()
{
return $this->belongsToMany(Role::class);
}
}
Please or to participate in this conversation.