【问题标题】:Laravel Eloquent to get relational table data by one column as a key and another as valueLaravel Eloquent 通过一列作为键,另一列作为值来获取关系表数据
【发布时间】:2020-07-08 09:00:33
【问题描述】:

我有两个表 usersuser_profiles 具有以下架构

用户表

  • 身份证
  • 用户名
  • 电子邮件
  • 密码
  • 角色
  • is_root
  • created_at
  • updated_at

用户个人资料表

  • 身份证
  • user_id (FK -> users -> id)
  • 价值

用户模式

public function profileData()
{
    return $this->hasMany(UserProfile::class);
}

用户配置文件模式

public function user()
{
    return $this->belongsTo(User::class);
}

所以如果我使用$user->profileData,它会给我这个结果,这是正确的。

=> Illuminate\Database\Eloquent\Collection {#3244
     all: [
       App\UserProfile {#3251
         id: 3,
         user_id: 10,
         key: "country",
         value: "India",
       },
       App\UserProfile {#3242
         id: 1,
         user_id: 10,
         key: "first_name",
         value: "John",
       },
       App\UserProfile {#3252
         id: 2,
         user_id: 10,
         key: "last_name",
         value: "Doe",
       },
     ],
   }

问题

但是,我想通过提供 key 字段值来从 user_profiles 表中获取 value 字段的值/数据 用户身份。例如,如果我通过 country 它应该返回 Indiafirst_name 然后 John 在上面的例子中。如何 做到了吗?

【问题讨论】:

  • @BohdanPetrenko 非常感谢您的回复。可能我解释得不好。我正在寻找的是一个关键的项目。所以如果我通过country 它应该返回India 等等。
  • $user->profileData->firstWhere('key', $key)->value 或 $user->profileData()->where('key', $key)->first()->value`
  • UserProfile::where('user_id', $id)->where('key', $key)->first()->vallue
  • 我认为问题不在于。问题是如果用户没有设置该字段,则记录将不可用。在这种情况下,它给出了错误。
  • UserProfile::where('user_id', $id)->where('key', $key)->select(['key','value'])->value('value')

标签: laravel eloquent eloquent-relationship


【解决方案1】:

您需要使用where()select()value() 语句来获取所需的值

UserProfile::where('user_id', $id)->where('key', $key)->select(['key','value'])->value('value')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-27
    • 1970-01-01
    • 2014-12-10
    • 2018-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-24
    相关资源
    最近更新 更多