2016-08-08 18 views
1

使用此:在Laravel雄辩,为什么这不正确选择(没有条件)?

profile = User::find($user)->with('profile')->first();

将返回,而不是选择属于找到的用户ID的配置文件的SELECT * FROM profiles查询。

我的用户模型如下:

public function profile() { 
    return $this->hasOne('App\Models\UserProfile', 'user_id'); 
} 

为什么不添加where条件?

+0

您是否尝试对它们进行重新排序:User :: with('profile') - > find($ user) - > first();' – TheFallen

回答

1

确实什么find($id)是扩大你的查询,例如:

// from 
User::find($user) 
// to 
User::where('id', $user)->take(1)->get('*')->first() 

换句话说:它创建的查询时,它限制了第一行,获取该行 - 返回集合 - 然后返回该集合中的第一个项目。

这意味着您的with('profile')被附加到对象而不是查询生成器,然后您再次调用first()

你应该做的,而不是为

User::with('profile')->find($user); 

...我假设的作品,但我没有测试它。 :)