Laravel Eloquent 通过一列作为键,另一列作为值来获取关系 table 数据

Laravel Eloquent to get relational table data by one column as a key and another as value

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

用户Table

用户个人资料Table

用户模式

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",
       },
     ],
   }

Question

However, I wan to fetch the value field's value/data from the user_profiles table by providing the key fields value by user id. For instance, if I pass the country it should return India or first_name then John in the above example. How to achieve that?

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

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