【问题标题】:Undefined relation on laravel 5laravel 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 
.......................

【问题讨论】:

  • 你能粘贴完整的模型类吗

标签: php database orm laravel-5 eloquent


【解决方案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}。希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-14
    • 2017-04-02
    • 2019-05-07
    • 2020-01-28
    • 1970-01-01
    • 2018-05-05
    相关资源
    最近更新 更多