使用 laravel 急切加载选择特定列不起作用

Posted

技术标签:

【中文标题】使用 laravel 急切加载选择特定列不起作用【英文标题】:Selecting specific columns using laravel eager loading doesn't work 【发布时间】:2017-12-10 06:46:11 【问题描述】:

当我尝试返回特定列时,我真的不明白为什么这种急切加载不起作用。 这段代码完美运行

$user=User::where('userName', $userName)
        ->with('points')
        ->with('examstaken')
        ->with('question')
        /*->with(array('points'=>function($query)
                $query->select('id','points');
         ))*/
         ->get();

这段代码不行

$user=User::where('userName', $userName)
        /*->with('points')*/
        ->with('examstaken')
        ->with('question')
        ->with(array('points'=>function($query)
                $query->select('id','points');
         ))
         ->get();

不起作用意味着,'points' 不返回任何值,而第一个正确返回值..

知道它有什么问题吗?

这是我的用户模型中的关系

  public function points()

    return $this->hasMany('App\Points','user_id');

谢谢..

【问题讨论】:

【参考方案1】:

好的解决了。看来我必须传递 user_id、外键然后它们才能工作。将其发布为答案,因为其他人可能会得到帮助:)

$user=User::where('userName', $userName)
        /*->with('points')*/
        ->with('examstaken')
        ->with('question')
        ->with(array('points'=>function($query)
                $query->select('user_id','points');
         ))
         ->get();

【讨论】:

如果不选择关系所需的键,Eloquent 将无法通过键将孩子与父母匹配

以上是关于使用 laravel 急切加载选择特定列不起作用的主要内容,如果未能解决你的问题,请参考以下文章