我正试图建立一对多的关系与2种模式,User和Role。因此,我希望一个User只能有一个角色,并且Role可以分配给多个User。我试着学习关于https://laravel.com/docs/5.1/eloquent-relationships#one-to-many的官方教程,最后得到了以下内容:
class User extends Model
{
public function role()
{
return $this->belongsToMany('App\Admin\Role');
}
}
class Role extends Model
{
protected $table = 'roles';
public function users()
{
return $this->hasMany('App\Admin\User');
}
}基于这个链接,我认为Role和Post是一样的,一个Role可以分配给多个User。但是,这不太有效,下面是我如何尝试访问特定User的角色名称
$role_first = $user->role; // Eloquent\Collection
$role_second = $user->role(); // Eloquent\Relations\BelongsToMany
$role_first->role_title // 'Undefined property: Illuminate\Database\Eloquent\Collection::$role_title'
$role_second->role_title // exception 'ErrorException' with message 'Undefined property: Illuminate\Database\Eloquent\Relations\BelongsToMany::$role_title'这里到底出了什么问题?
发布于 2016-03-06 19:10:22
在User类中
public function role()
{
// not $this->belongsToMany('App\Admin\Role');
return $this->belongsTo('App\Admin\Role');
}因为你想要的是oneToMany而不是manyToMany关系。
发布于 2016-03-06 19:15:42
这样就行了。请试试看
class User extends Model
{
public function role()
{
return $this->hasOne(App\Admin\Role::class);
}
}
// user belongs to one role
class Role extends Model
{
protected $table = 'roles';
public function users()
{
return $this->belongsTo(App\Admin\User::class);
}
}发布于 2016-03-06 19:57:35
用户模型
class User extends Authenticatable{
public function roles(){
return $this->belongsTo('App\Admin\Role');
}
}角色模型
class Role extends Model{
public function users(){
return $this->hasMany('App\Admin\User');
}
}用户只能有一个角色,该角色可以分配给许多用户。
https://stackoverflow.com/questions/35831139
复制相似问题