简体   繁体   中英

Laravel get a single row from hasMany Relation

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM