duanri1985 2015-09-11 08:39
浏览 141
已采纳

Laravel从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();
}
  • 写回答

1条回答 默认 最新

  • donglie1898 2015-09-11 09:18
    关注

    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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法