Laravel为模型中的现有值返回null

时间:2020-06-03 19:12:40

标签: laravel laravel-7

Controller中的数据库获取查询后,我得到以下输出:

$newTickets = Ticket::with('user')->whereStatus(0)->orderBy('id', 'desc')->take(5)->get();

dd($newTickets[0]->user);

输出:

#attributes: array:18 [▼
    "id" => 1
    "active" => 1
    "name" => "user1"
    "family" => "user1111"
    "username" => "xxxxx"
    "avatar" => "user_bg3.jpg"
    "email" => "p@p.com"
    "email_verified_at" => null
    "user_id" => null
    "properties_id" => null
    "password" => "$2y$10$b50fMYQMfMyJgtgCDEfQyueu.C.VfhfQCXT/f2Y8ObAe4nMrNiXEe"
    "mobile_number" => "333333"
    "device_id" => "0123456789"
    "api_token" => "aaaaaaa"
    "remember_token" => null
    "deleted_at" => null
    "created_at" => "2020-06-02 13:13:15"
    "updated_at" => "2020-06-02 13:13:15"
]

现在,当我尝试显示avatar字段值时,我会得到null:|

dd($newTickets[0]->user->avatar);

输出:

null

什么问题以及为什么我无法获得该值并返回null?

我可以得到另一个值,而我的问题只是得到avatar

User模型:

class User extends Authenticatable
{
    use Notifiable, SoftDeletes;

    protected $guarded = [
        'id',
    ];
    protected $hidden = [
        'password', 'remember_token',
    ];

    protected $casts = [
        'email_verified_at' => 'datetime',
        'avatar' => 'array',
    ];

    public function group()
    {
        return $this->belongsToMany(UserGroup::class, 'user_user_group');
    }

    public function child()
    {
        return $this->hasMany(User::class)->with('child');
    }

    public function parent()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function blogs()
    {
        return $this->hasMany(UserBlog::class);
    }

    public function setPasswordAttribute($password)
    {
        $this->attributes['password'] = Hash::make($password);
    }

    public function getFullNameAttribute()
    {
        return $this->name.' '.$this->family;
    }
}

1 个答案:

答案 0 :(得分:1)

您正在将头像转换为数组... 当您这样做时... laravel自动解码json中的“头像”以进行输出并将其编码为输入... more details

只需从删除头像:

  protected $casts = [
        'email_verified_at' => 'datetime',
        'avatar' => 'array',
    ];