【发布时间】:2018-08-03 08:10:57
【问题描述】:
我定义了一个关系
class people {
public function hobbies() {
return $this->hasMany(hobby::class, "people_id")->select(['name', 'action', 'effect']);
}
}
我尝试通过急切加载来加载
people::with('hobbies')->get();
最终我的hobbies 的结果总是空的,然后我发现这是因为选择过滤器在people 到hobbies 的关系中没有people_id 喜欢
public function hobbies() {
return $this->hasMany(hobby::class, "people_id")->select(['people_id', 'name', 'action', 'effect']);
}
那我现在有个问题,为什么select过滤器需要外键?
对于一个sql查询,select hobbies.name, hobbies.action, hobbies.effect from hobbies join people on hobbies.people _id = people.id就足够取回数据了?
【问题讨论】:
-
你可能想从你的模型中删除
select()并这样做以使CDE::with('ABC:id,foo,bar')->get();更有活力,甚至像这样CDE::with(['ABC', function($query) { $query->select('id', 'foo', 'bar', 'created_at', 'whatever'); }])->get(); -
您应该始终在关系模型中选择 relations key 列。如果你不选择那么雄辩的找不到相关行。
-
如果您将
ABC, CDE替换为您的实际model名称会更好。人们会更容易为您提供帮助。 -
@اسماعیلزارع,不,因为它是来自人们的加入,我已经与 people.id 对吗?只是更容易从 hobbies.people_id 访问,可以直接从 people.id 分配 hobbies_people_id。在人模型中,我使用
get(),所以人模型中的所有数据都被检索到,对于人模型关系模型,当外键为空时,可以从人那里检查并抓取它吗? -
@AH.Pooladvand 我使用 select 的原因,只是为了从数据库中检索较小的字段。而对于你写的第二种方法
CDE::with(['ABC', function($query) { $query->select('id', 'foo', 'bar', 'created_at', 'whatever'); }])->get();,我不确定这种方式,当记录为25时,它会查询26次,因为预加载的建议是最小化从26到2的过程。
标签: php sql laravel eloquent eager-loading