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

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

图片转代码服务由CSDN问答提供 功能建议

我有以下数据库结构:

  users 
 ________  
id 
 
user_fields 
 ________ 
id 
name 
 
user_field_values 
 ________ 
id 
user_id 
field_id 
value 
   
 
 

我有一个基本的hasMany关系 UserFieldValues但这看起来很糟糕,特别是因为我不想迭代整个Relation只是为了在特定的user_fields.name上获得特定的user_field_values.value。

所以我想要的 get是来自当前用户的user_fields_values.value,其中user_fields.name =?

我的想法是创建一个belongsToMany关系但我不能让它工作。

我真的很感激你的帮助。

解决方案

感谢 LêTrầnTiếnTrung,“load”是我要找的关键字。

  public function userFields(){
 return $ this-> belongsToMany('\ App \  Models \ UserFields',“user_field_values”,'user_id','field_id') - > withPivot('value'); 
} 
 
公共函数userField($ fieldName){
 $ this-> load(  ['userFields'=>函数($ q)使用($ 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;
    }
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题