Laravel 预加载 with() 不适用于自定义列

Laravel eager loading with() not working with custom columns

我的 Component 模型中有以下关系:

public function subComponent()
{
    return $this->belongsTo(SubComponent::class, 'code', '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');

如果我执行第二条语句,它会给出正确的结果。但它不适用于组件集合。 此行为并不适用于所有组件。他们中的大多数人确实渴望加载他们的子组件。但是其他一些人则描述了这种奇怪的行为。我找不到原因。

我认为问题出在你的关系声明上。
当你声明这个时:

public function subComponent()
{
    return $this->belongsTo(SubComponent::class, 'code', 'code');
}

表示你的Component属于一个subComponent。我认为恰恰相反。您应该像这样重新声明您的子组件关系:

  1. if Component --HasOne--> SubComponent
public function subComponent()
{
    return $this->hasOne(SubComponent::class, 'code', 'code');
}
  1. If Component --HasMany--> SubComponent
public function subComponent()
{
    return $this->hasMany(SubComponent::class, 'code', 'code');
}

此修复应该可以解决您的问题。