【问题标题】:Return Single column from HasOne laravel from model从模型中返回 HasOne laravel 的单列
【发布时间】:2021-04-12 19:18:46
【问题描述】:

我将用户图像保存在不同的表中,我希望在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"
},

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

【问题讨论】:

    标签: laravel eloquent relation


    【解决方案1】:

    使用 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;
    

    【讨论】:

    • 谢谢,但是,我可以在模型本身做些什么吗?
    • 您可以将其设置为 User 模型的属性。
    • @Gaurav 你测试了吗?
    【解决方案2】:

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

    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);
    

    这会对您有所帮助,但最好使用 Resources 进行 api 响应来转换某些特定字段。

    【讨论】:

    • 如果 Image 函数返回 null 怎么办?
    • 你可以在上面写条件。
    • 在 null 上调用成员函数 addEagerConstraints()。
    • 对返回的关系使用可选方法
    • 我使用了第一种方法,它给出了Trying to get property 'image' of non-object 和其他方法在 null 上调用了成员函数 addEagerConstraints()
    【解决方案3】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2016-02-29
      • 2014-11-29
      • 2022-01-05
      • 2017-05-02
      • 2023-02-16
      • 1970-01-01
      • 1970-01-01
      • 2016-09-27
      • 1970-01-01
      相关资源
      最近更新 更多