Laravel急切的加载()不使用自定义列
我在组件
模型中具有以下关系:
public function subComponent()
{
return $this->belongsTo(SubComponent::class, 'code', 'code');
}
两者都有一个名为代码
的列,带有数据类型字符串。代码的一个示例将只是“ ab1234 ”。
我尝试基于此代码将组件及其子组件加载在一起:
Component::with('subComponent')->get();
由于某种原因,现在没有将一些记录加载到其易渗透组件上。有趣的部分是,如果我不急切地加载它,那就是在起作用:
Component::where('code', 'ABC1234')->first()->subComponent;
但这仅发生在特定的子组件上。他们中的大多数人都可以急切地加载,我找不到其他人没有加载的原因。我已经激活 https://github.com/barryvdh/laravel-debugbar 调查发生的事情在背景中,但这似乎是绝对正确的:
select * from `components` where `code` = 'ABC1234' limit 1;
select * from `sub_components` where `sub_components`.`code` in ('ABC1234');
如果我执行第二个语句,它将给我带来适当的结果。但是它不应用于组件集合。 这种行为不适用于所有组件。他们中的大多数渴望加载子组件。但是其他一些人描述了奇怪的行为。我找不到原因。
I have the following relationship in my Component
model:
public function subComponent()
{
return $this->belongsTo(SubComponent::class, 'code', 'code');
}
Both have a column called code
with data type string. One example for a code would simply be "AB1234".
I try to load components together with their sub components based on this code:
Component::with('subComponent')->get();
Now a few records are not loaded with their resceptive component for some reason. The interesting part is that is is working if I do not eager load it:
Component::where('code', 'ABC1234')->first()->subComponent;
But this only happens to specific sub components. Most of them can be eager loaded and I cannot find a reason why others are not loaded. I have activated https://github.com/barryvdh/laravel-debugbar to investigate what happens in the background but it seems absolutely correct:
select * from `components` where `code` = 'ABC1234' limit 1;
select * from `sub_components` where `sub_components`.`code` in ('ABC1234');
If I execute the second statement it is giving me the proper result. But it is not applied to the component collection. This behaviour does not apply to all components. Most of them do eager load their sub component. But some others have this described odd behaviour. I cannot find the reason why.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为问题是由于您的关系声明。
当您声明以下内容时:
这意味着您的
组件
属于subcomponent
。我认为这是相反的。您应该像这样重新列出子组件关系:组件
- hasone - >sub-component
component
< strong> - Hasmany - &gt;子组件
本修复程序应解决您的问题。
I think the problem is due to your relation declaration.
When you declare this :
It means that your
Component
belongTo asubComponent
. I think it is the opposite. You should redeclare your subComponent relation like this :Component
--HasOne-->SubComponent
Component
--HasMany-->SubComponent
This fix should solve your problem.