[英]How to define relation in laravel 5.3 eloquent model?
I have tables in my database schema as follows, 我的数据库架构中有以下表格,
Is it pivot table? 是数据透视表吗?
How can I define relationship in eloquent model? 如何在雄辩的模型中定义关系?
class Role extends Model {
public $timestamps = false;
public function permissions() {
return $this->hasMany('App\Models\RolePermission', 'permissions_id');
}
}
Is this correct way to define relationship? 这是定义关系的正确方法吗? Please help me to understand.
请帮助我理解。
and 和
class RolePermission extends Model {
public $timestamps = false;
public function role() {
return $this->belongsTo('App\Models\Role', 'roles_id');
}
}
The problem is that you need to name your table permission_role
to follow the design pragma. 问题是,你需要命名表
permission_role
遵循设计编译。
Schema::create('roles', function(Blueprint $table){
$table->increments('id');
$table->string('name');
$table->timestamps();
});
Schema::create('permissions', function(Blueprint $table){
$table->increments('id');
$table->string('name');
$table->timestamps();
});
Then you just need the permission_role
table: 然后,您只需要
permission_role
表:
Schema::create('permission_role', function(Blueprint $table){
$table->increments('id');
$table->integer('permission_id')->unsigned();
$table->foreign('permission_id')->references('id')->on('permissions')->onDelete('cascade');
$table->integer('role_id')->unsigned();
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
});
Then you just set up your models like this: 然后,您可以像这样设置模型:
class Role {
public function permissions() {
return $this->hasMany(App\Permission::class);
}
}
Then of course your permission class 然后当然是您的许可课程
class Permission {
public function role() {
return $this->belongsToMany(App\Role::class);
}
}
its a many to many relationship bond together by a pivot table Permission_Role. 它通过数据透视表Permission_Role将多对多关系绑定在一起。 there for each table belongsToMany not hasOne or hasMany
对于每个表,belongsToMany都没有hasOne或hasMany
class Role {
public function permissions() {
return $this->belongsToMany(App\Permission::class);
}
}
class Permission {
public function role() {
return $this->belongsToMany(App\Role::class);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.