【发布时间】:2015-09-29 03:03:57
【问题描述】:
在 Laravel 5.1 中,我可以看到表列关系可以通过两种方式设置:
1) 在迁移表中定义外键。
2) 在模型中定义 Eloquent 关系。
我已阅读文档,但我仍然对以下内容感到困惑:
我需要同时使用还是只需要 1 个?
两者同时使用有错吗?还是成功了 冗余或引起冲突?
使用 Eloquent 关系而不提及 迁移列中的外键?
有什么区别?
这些是我现在拥有的代码。如果我需要删除我在迁移文件中设置的外键,我仍然不清楚。
迁移:
public function up()
{
Schema::create('apps', function (Blueprint $table) {
$table->increments('id');
$table->string('app_name');
$table->string('app_alias');
$table->timestamps();
$table->engine = 'InnoDB';
});
// This is the second Migration table
Schema::create('app_roles', function (Blueprint $table) {
$table->increments('id');
$table->integer('app_id')->unsigned()->index();
$table->integer('user_id')->unsigned()->index();
$table->integer('role_id')->unsigned()->index();
$table->engine = 'InnoDB';
$table->unique(array('app_id', 'user_id'));
$table->foreign('app_id')
->references('id')
->on('apps')
->onDelete('cascade');
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
$table->foreign('role_id')
->references('id')
->on('roles')
->onDelete('cascade');
});
}
具有雄辩关系的模型:
// App Model
class App extends Model
{
public function appRoles() {
return $this->hasMany('App\Models\AppRole');
}
}
// AppRole Model
class AppRole extends Model
{
public function app() {
return $this->belongsTo('App\Models\App');
}
public function user() {
return $this->belongsTo('App\User');
}
public function role() {
return $this->belongsTo('App\Models\Role');
}
}
// User Model
class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
.....
public function appRole() {
return $this->belongsToMany('App\Models\AppRole');
}
}
// Role Model
class Role extends EntrustRole
{
public function appRole() {
return $this->hasMany('App\Models\AppRole');
}
}
有人可以帮我理解一下吗?
【问题讨论】:
标签: php mysql laravel eloquent laravel-5