【发布时间】:2020-07-08 09:00:33
【问题描述】:
我有两个表 users 和 user_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它应该返回India或first_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