简体   繁体   English

Laravel从hasMany Relation中获得一行

[英]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. 我在UserFieldValues上有一个基本的hasMany关系,但这对我来说很糟糕,尤其是因为我不想为了获得特定user_fields.name上的特定user_field_values.value来迭代整个Relation。

So what i want to get is a user_fields_values.value from the current user where user_fields.name = ? 所以我想从当前用户那里获得一个user_fields_values.value,其中user_fields.name =吗?

My idea is to make a belongsToMany Relation but I dont get it to work. 我的想法是建立一个belongsToMany关系,但是我没有使它起作用。

I really would appreciated your help. 我真的很感谢您的帮助。

Solution

Thanks to Lê Trần Tiến Trung, "load" was the keyword i was looking for. 感谢LêTrầnTiếnTrung,“ load”是我一直在寻找的关键字。

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. 最简单的方法是使用belongsToMany,withPivot获取值,添加where子句以正确选择关系。 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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