以下是我的查询
$user = User::select(['uuid','name','about'])->with(['education','work'])->first();
这将返回关系education
和work
的空数据,
但是如果我从查询中删除select
函数,我会在关系中获取数据,并且它还会返回我不想要的用户表的所有列。
如何解决这个问题
答案 0 :(得分:2)
问题是关系(with(...)
)执行额外的查询以获取相关结果。我们假设您有一对多的关系users
有很多works
。然后User::with('work')->find(1)
将执行这两个查询:
select user where id = 1
和select works where user_id = 1
。
因此,基本上为了能够执行第二个查询(获取关系数据),您需要在select语句中包含id
(或您引用的任何列)。
修正:
$user = User::select(['uuid','name','about', 'id'])->with(['education','work'])->first();
不同形式的相同原则适用于所有关系。例如,在hasMany
的倒数belongsTo
中,您需要选择外键(例如user_id
)。