【问题标题】:Undefined property in model模型中未定义的属性
【发布时间】:2023-04-09 09:59:01
【问题描述】:

用户模型:

class User extends Authenticatable
{
    use Notifiable;

    protected $table = 'users';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token', 'role_id',
    ];

    protected $appends = [
        'role',
    ];

    public function getRoleAttribute()
    {
        return $this->role->name;
    }

    /**
     * User role.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function role()
    {
        return $this->belongsTo('App\Role');
    }
}

我不想显示角色名称,而是显示角色 ID。

但它说:

User.php 第 38 行中的 ErrorException: 未定义属性:App\User::$role

角色表包含​​ idname

用户表包含一个role_id

编辑:

当我尝试return $this->role()->name; 时,它给了我一个:

User.php 第 38 行中的 ErrorException: 未定义属性:Illuminate\Database\Eloquent\Relations\BelongsTo::$name

但是我检查了角色并且有效...

/**
 * Check if the user is an admin.
 *
 * @return bool
 */
public function isAdmin()
{
    if ($this->role->name == 'admin') {
        return true;
    }

    return false;
} 

【问题讨论】:

    标签: php laravel laravel-eloquent


    【解决方案1】:

    这是因为你有 role 属性和 role 关系,尝试重命名其中一个,它会与return $this->role->name;一起工作

    【讨论】:

    • 哇,你是最棒的,我有点说得通。。谢谢
    【解决方案2】:

    使用关系,而不是属性:

    {{ $user->role()->name }}
    

    【讨论】:

    • 未定义属性:Illuminate\Database\Eloquent\Relations\BelongsTo::$name
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-20
    相关资源
    最近更新 更多