Php 为什么在laravel eloquent中使用load()时$this是空的?
我有这两张桌子Php 为什么在laravel eloquent中使用load()时$this是空的?,php,laravel,eloquent,Php,Laravel,Eloquent,我有这两张桌子 components ========================= | id | code | type | ========================= | 1 | E1 | Engine | | 2 | G1 | Generator | | 3 | E2 | Engine | ========================= formulas /* engine_id and generator_id reference
components
=========================
| id | code | type |
=========================
| 1 | E1 | Engine |
| 2 | G1 | Generator |
| 3 | E2 | Engine |
=========================
formulas /* engine_id and generator_id reference to component id */
=============================================
| id | engine_id | generator_id | diesel_id |
=============================================
| 1 | 1 | 2 | 1 |
| 2 | 3 | 2 | 1 |
=============================================
因此,在Model/Component.php中,我创建了这个雄辩的函数
public function formulas()
{
$foreignKey = $this->type === 'Engine' ? 'engine_id' : 'generator_id';
return $this->hasMany(Formula::class, $foreignKey);
}
如果我使用$component->formulas
,它可以正常工作。但我也必须为每种配方奶粉打电话给迪塞尔。我不喜欢在循环中使用load()
// ComponentController.php
public function show(Component $component)
{
$component->formulas->each(function ($formula) {
//if this component has 100 formulas, then it will do 100 query to table diesels
$formula->load('diesel');
});
return $component;
}
因此我想使用$component->load('formulas.diesel')
,但$this
始终为空,外键将始终设置为'generator\u id'
// Component.php
public function formulas()
{
$foreignKey = $this->type === 'Engine' ? 'engine_id' : 'generator_id';
info($this); // this will be called twice, but only first call has value.
return $this->hasMany(Formula::class, $foreignKey);
}
// ComponentController.php
public function show(Component $component)
{
info('=== 1 ===');
$component->formulas;
info('=== 2 ===');
return $component->load('formulas');
}
// Outputs in Laravel.log
[2020-02-28 18:15:08] testing.INFO: === 1 ===
[2020-02-28 18:15:08] testing.INFO: {"id":1,"code":"E1","type":"Engine"}
[2020-02-28 18:15:08] testing.INFO: === 2 ===
[2020-02-28 18:15:08] testing.INFO: [] <------ why is this empty??
//Component.php
公共函数公式()
{
$foreignKey=$this->type=='Engine'?'Engine_id':'generator_id';
info($this);//将调用两次,但只有第一次调用才有值。
返回$this->hasMany(公式::类,$foreignKey);
}
//ComponentController.php
公共功能展示(组件$Component)
{
信息('==1==');
$component->formulas;
信息('==2==');
返回$component->load('formulas');
}
//Laravel.log中的输出
[2020-02-2818:15:08]testing.INFO:==1==
[2020-02-28 18:15:08]testing.INFO:{“id”:1,“code”:“E1”,“type”:“Engine”}
[2020-02-2818:15:08]testing.INFO:==2==
[2020-02-28 18:15:08]testing.INFO:[]使用->with()或->load()函数调用。
旨在解决N+1问题
这意味着Laravel不会为每个组件模型生成查询,如:
select * from formulas where engine_id = 1
select * from formulas where generator_id = 2
...
它将使用所有模型的ID调用一个查询,如:
select * from formulas where generator_id in (1, 2, 3, ...)
在这方面,您不能使用“this”,因为formulas()函数将从组件模型的“空实例”调用,只是为了标识关系
为了更好地理解,您可以阅读有关的文档。您知道在进行快速加载时,如果需要条件$this,应该怎么做吗?