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