从模型的 HasOne laravel 返回单列

问题描述

我将用户图像保存在不同的表中,并且希望在 User 模型中具有以下内容

public function Image()
{
    return $this->hasOne(UserImages::class,'user_id','id')->latest();
}

上述关系返回以下内容

"image": {
    "id": 3,"user_id": 1,"image": "http://live.test/uploads/user/User-Oss8MewXVzHZCehHoOUgkdYoo3N1K0gYI9jY69ZsnyiHnqHsHv.png","is_primary": 1,"created_at": "2021-04-12T08:01:47.000000Z","updated_at": "2021-04-12T08:01:47.000000Z"
},

我只想接收图像,我该怎么做?

解决方法

使用 value() 方法

$user->image()->value('image');

来自Eloquent documentation

如果您不需要整行,您可以使用 value 方法从记录中提取单个值。这个方法会直接返回列的值:

$email = DB::table('users')->where('name','John')->value('email');

您可以将其设置为用户属性。

public function getProfileImageAttribute()
{
    return optional($this->image)->image;
    //or
    return $this->image->image ?? null; 
    //or
    return $this->image->image ?? 'path/of/default/image';
}

现在你可以这样称呼它

$user->profile_image;
,

您可以在模型中创建另一个函数并访问之前的方法,如

public function image()
{
  return $this->hasOne(UserImages::class,'user_id','id')->latest();
}

public function avatar()
{
  return $this->image->image ?: null;
  //OR
  return $this->image->image ?? null;
  //OR
  return !is_null($this->image) ? $this->image->image : null;
  //OR
  return optional($this->image)->image;
}

它可以通过 $user->avatar();

访问

根据讨论,您正在向 api 发送响应

$this->user = $this->user->where('id',"!=",$current_user->id)->with(['chats','Image:user_id,image'])->paginate(50);

这对你有帮助,但最好使用 api 响应的资源来转换一些特定的字段。

,

你可以使用 Laravel 提供的魔法:

$user->image->pluck('profile_image');

文档:https://laravel.com/docs/8.x/collections#method-pluck