【发布时间】:2016-04-12 11:05:57
【问题描述】:
我有两张桌子:
用户(id,nom,role_id(fk),...) 角色(id,角色)
在我创建的用户模型中:
public function role()
{
return $this->belongsTo('App\Role','role_id');
}
public function hasRole($role)
{
$role = $this->role();
if (!is_null($role)) {
$role = $role->role;
}
return ($user_role===$role) ? true : false ;
}
public function whatRole()
{
$user_role = $this->roles();
if (!is_null($user_role)) {
$user_role = $user_role->role;
return $user_role;
}else{
return false;
}
}
我在角色模式中创建:
public function user()
{
return $this->hasMany('App\User');
}
但是当我尝试像这样使用它时:Auth::user()->hasRole('medecin')
我收到此错误:
ErrorException in User.php line 25: Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$role (View: C:\wamp\www\Medecin2016\resources\views\pages\role_form.blade.php)
in User.php line 25
at CompilerEngine->handleViewException(object(ErrorException), '1') in PhpEngine.php line 43
at PhpEngine->evaluatePath('C:\wamp\www\Medecin2016\storage\framework\views/018276e247e24f69812c603a17c57319', array('__env' => object(Factory), 'app' => object(Application), 'errors' => object(ViewErrorBag))) in CompilerEngine.php line 57
at CompilerEngine->get('C:\wamp\www\Medecin2016\resources\views/pages/role_form.blade.php', array('__env' => object(Factory), 'app' => object(Application), 'errors' => object(ViewErrorBag))) in View.php line 142
at View->getContents() in View.php line 111
at View->renderContents() in View.php line 80
.......................
【问题讨论】:
-
你能粘贴完整的模型类吗
标签: php database orm laravel-5 eloquent