在 Laravel Eloquent 中,为什么选择不正确(没有 where 条件)?
In Laravel Eloquent, why is this not selecting properly (no where condition)?
使用这个:
profile = User::find($user)->with('profile')->first();
将 return 查询 SELECT * FROM profiles
,而不是选择属于找到的用户 ID 的配置文件。
我的用户模型如下:
public function profile() {
return $this->hasOne('App\Models\UserProfile', 'user_id');
}
为什么不添加 where
条件?
find($id)
真正做的是扩展您的查询,如下所示:
// from
User::find($user)
// to
User::where('id', $user)->take(1)->get('*')->first()
换句话说:它创建查询,将其限制在第一行,获取该行 - returns 一个集合 - 然后 returns 该集合中的第一项。
这意味着您的 with('profile')
会附加到对象,而不是查询生成器,然后您再对它进行 first()
调用。
你应该做的是
User::with('profile')->find($user);
...我认为可以,但我还没有测试过。 :)
使用这个:
profile = User::find($user)->with('profile')->first();
将 return 查询 SELECT * FROM profiles
,而不是选择属于找到的用户 ID 的配置文件。
我的用户模型如下:
public function profile() {
return $this->hasOne('App\Models\UserProfile', 'user_id');
}
为什么不添加 where
条件?
find($id)
真正做的是扩展您的查询,如下所示:
// from
User::find($user)
// to
User::where('id', $user)->take(1)->get('*')->first()
换句话说:它创建查询,将其限制在第一行,获取该行 - returns 一个集合 - 然后 returns 该集合中的第一项。
这意味着您的 with('profile')
会附加到对象,而不是查询生成器,然后您再对它进行 first()
调用。
你应该做的是
User::with('profile')->find($user);
...我认为可以,但我还没有测试过。 :)