我不明白关系船是如何与Eloquent合作的。假设一个用户具有一个角色。我在我的模型用户中写了这个:
public function role()
{
return $this->hasOne('AppModelsRole');
}
而这在我的模型角色中:
public function user()
{
return $this->belongsTo('AppUser');
}
之后我想检索连接用户的角色,如下所示:
Auth::user()->role->role_name
但它抛出了一个异常:
Undefined column: 7 ERROR: column roles.user_id does not exist
它不是那样工作的吗?
您在角色表中缺少user_id
外列,Eloquent 假定该列存在,以便将User
与Role
Schema::create('roles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('role_name');
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamps();
});
更新:给定一个关系
AppUser
模型
public function role()
{
return $this->hasOne('AppModelsRole');
}
AppModelRole
模型
public function user()
{
return $this->belongsTo('AppUser');
}
DatabaseSeeder
$user = factory('AppUser')->create();
$user->role()->create([
'role_name' => 'Admin'
]);
routes/web
use IlluminateSupportFacadesAuth;
Route::get('/', function () {
return Auth::user()->role->role_name;
});
Results
=>管理员
您应该在用户模型中使用角色关系的belongsTo()
关系:
public function role()
{
return $this->belongsTo('AppModelsRole');
}