【问题标题】:Laravel relationship not working but foreign key has a valueLaravel 关系不起作用但外键有价值
【发布时间】:2023-04-03 08:51:02
【问题描述】:

我有一个用户模型,在模型中我有一个名为 role_id 的整数字段。如果我回显该值 {{ $user->role_id }} 我会得到一个数字,我也会在用户模型与角色模型上建立关系,但如果我尝试执行 {{ $user->role()->role_name }} 我会收到以下错误:

Undefined property: Illuminate\Database\Eloquent\Relations\HasOne::$role_name 

如果我使用代码{!! \App\Models\Role::whereKey($user->role_id)->pluck('role_name') !!},我得到的值是正确的,所以它与我看不到它在哪里的关系有关。

用户模型

public function role()
{
    return $this->hasOne('\App\Models\Role');
}

榜样

class Role extends Model

{ 使用软删除;

public $table = 'roles';

const CREATED_AT = null;
const UPDATED_AT = null;


protected $dates = ['deleted_at'];


public $fillable = [
    'role_name'
];

/**
 * The attributes that should be casted to native types.
 *
 * @var array
 */
protected $casts = [
    'id' => 'integer',
    'role_name' => 'string'
];

/**
 * Validation rules
 *
 * @var array
 */
public static $rules = [

];

public function users(){
    return $this->belongsTo('App\Models\User');
}

【问题讨论】:

    标签: php relationships laravel-5.6


    【解决方案1】:

    您应该使用魔术属性$role 而不是关系定义方法role()。试试这个:

    {{ $user->role->role_name }}
    

    【讨论】:

    • uuuggghhhh 这就是我生病和疲倦时不编码的原因,谢谢!
    猜你喜欢
    • 2017-08-16
    • 2020-05-13
    • 1970-01-01
    • 2017-08-17
    • 2021-01-01
    • 1970-01-01
    • 2015-09-24
    • 2019-07-20
    • 2018-11-25
    相关资源
    最近更新 更多