我不明白relationShips是如何使用Eloquent的。想象一下,一个用户只有一个角色。我在我的模型用户中写道:
public function role()
{
return $this->hasOne('App\Models\Role');
}这是我的模范角色:
public function user()
{
return $this->belongsTo('App\User');
}在此之后,我想检索连接的用户的角色,如下所示:
Auth::user()->role->role_name但是它抛出了一个异常:
Undefined column: 7 ERROR: column roles.user_id does not exist不是这样的吗?
发布于 2019-09-11 23:22:22
roles表中缺少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();
});更新:给定一个hasOne关系
App\User模型
public function role()
{
return $this->hasOne('App\Models\Role');
}App\Model\Role模型
public function user()
{
return $this->belongsTo('App\User');
}DatabaseSeeder
$user = factory('App\User')->create();
$user->role()->create([
'role_name' => 'Admin'
]);routes/web
use Illuminate\Support\Facades\Auth;
Route::get('/', function () {
return Auth::user()->role->role_name;
});Results => 管理员
发布于 2019-09-11 23:23:17
对于角色关系,您应该在用户模型中使用belongsTo()关系:
public function role()
{
return $this->belongsTo('App\Models\Role');
}https://stackoverflow.com/questions/57892240
复制相似问题