2017-04-22 66 views
1

以下是我的查询Laravel雄辩选择功能引起的空关系

$user = User::select(['uuid','name','about'])->with(['education','work'])->first(); 

这个返回空数据关系educationwork, 但如果我从查询中删除select功能我在关系和获取数据也回报所有我不想要的用户表的列。

如何才能解决这个问题

回答

2

问题是关系(with(...))执行额外的查询来获得相关结果。假设你有一对多的关系,其中users有很多worksUser::with('work')->find(1)将执行这2个查询:

select user where id = 1select works where user_id = 1

因此,基本上为了能够执行第二个查询(获取关系数据),您需要在选择语句中包含id(或您所引用的任何列)。

修复:以不同的形式

$user = User::select(['uuid','name','about', 'id'])->with(['education','work'])->first(); 

原则同样适用于所有关系。例如在hasManybelongsTo的倒数中,您需要选择外键(例如user_id)。

+1

谢谢,这个作品! –