laravel 5上的未定义关系
Posted
技术标签:
【中文标题】laravel 5上的未定义关系【英文标题】:Undefined relation on laravel 5 【发布时间】: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
.......................
【问题讨论】:
你能粘贴完整的模型类吗 【参考方案1】:我认为您对模型有些混淆...使用 hasRole 方法,您想检查用户是否具有给定的角色(在您的情况下为“medicin”)。让我们检查您的代码以了解您实际上做错了什么:
public function hasRole($role)
// Here you override the given string: this means that you actually
// lose the 'medicin' value. Additionally, you're calling a method
// that defines the Eloquent relation. There is NO NEED to do
// anything like that. Maybe you want to call the $this->role
// property instead of the method...
$role = $this->role(); // REMOVE THIS
// Here you should check if the given string is empty or not
if ( !is_null($role) ) // Change is_null with empty is better (IMHO)
// Again, you're overriding the given string ('medicin')
//
// $role = $role->role;
// You are returning the Boolean value according to the result
return ($user_role===$role) ? true : false ;
现在,让我们尝试做一些更好的事情:按照以下方式更改方法应该可以解决问题:
public function hasRole($role = '')
if ( !empty($this->role) && $role === $this->role->FIELD )
return TRUE;
return FALSE;
使用角色表中的正确字段更改 FIELD。希望这会有所帮助。
【讨论】:
以上是关于laravel 5上的未定义关系的主要内容,如果未能解决你的问题,请参考以下文章
Laravel 有来自 tinker 的未定义常量 App\User
未定义的属性:Illuminate\Database\Eloquent\Relations\BelongsTo::$status。 Laravel 5.5 关系