Reputation: 210
I have the following database Structure:
users
________
id
user_fields
________
id
name
user_field_values
________
id
user_id
field_id
value
I have a basic hasMany Relation on UserFieldValues but this looks awful for me, especially because i don't want to iterate the whole Relation just to get a specific user_field_values.value on a specific user_fields.name.
So what i want to get is a user_fields_values.value from the current user where user_fields.name = ?
My idea is to make a belongsToMany Relation but I dont get it to work.
I really would appreciated your help.
Solution
Thanks to Lê Trần Tiến Trung, "load" was the keyword i was looking for.
public function userFields() {
return $this->belongsToMany('\App\Models\UserFields',"user_field_values", 'user_id', 'field_id')->withPivot('value');
}
public function userField($fieldName) {
$this->load(['userFields' => function($q) use ($fieldName) {
$q->where('slug', '=', $fieldName);
}])->first();
}
Upvotes: 0
Views: 4148
Reputation: 650
The easiest way is using belongsToMany, withPivot to get value, add where clause to select correctly relation. Here is example, not tested.
// User.php
public function fields()
{
return $this->belongsToMany('Field', 'user_field_values')->withPivot('value');
}
// query
$users = User::all();
$users->load(['fields' => function($q) use ($fieldName) {
$q->where('name', '=', $fieldName);
});
foreach ($users as $user) {
echo $user->fields->first()->pivot->value;
}
Upvotes: 3