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

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化