[英]Laravel DD helper not executing inside each function
我目前正在尝试通过复制具有适当关系的对象来解决问题。 我通常使用Laravel的DD帮助程序来查看我是否获得了正确的信息,但是在这种情况下,当它到达要执行的方法中的那一行时,我不认为它正在运行。
这是我处理重复的控制器方法。
$copiedManagementSystem = $managementSystem->replicate();
$copiedManagementSystem->inspections->each(function($inspection) {
$copiedInspection = $copiedManagementSystem->inspections()->create([
'name' => $inspection->name,
'management_system_id' => $inspection->managementSystemId,
'pass_score' => $inspection->passScore,
'max_score' => $inspection->maxScore,
'order' => $inspection->order,
]);
dd($inspection); //I've placed the dd here but it doesn't work in any position, in any part of the each function.
$inspection->checks->each(function($check){
$copiedInspection->checks()->create([
'question' => $check->question,
'values' => $check->values,
'type' => $check->type,
'inspection_id' => $check->inspectionId,
'order' => $check->order,
]);
});
});
$copiedManagementSystem->save();
这是带有检查关系的管理系统模型
class ManagementSystem extends Model
{
protected $table = 'management_systems';
protected $fillable = ['name', 'description'];
public function inspections()
{
return $this->hasMany(Inspection::class);
}
}
这是检验与关系的模型
class Inspection extends Model
{
protected $table = 'inspections';
protected $casts = [
'order' => 'integer'
];
protected $fillable = [
'name',
'management_system_id',
'pass_score',
'max_score',
'order'
];
public function checks()
{
return $this->hasMany(Check::class);
}
public function managementSystem()
{
return $this->belongsTo(ManagementSystem::class);
}
}
最后,这是检查模型及其关系。
class Check extends Model
{
protected $table = 'checks';
protected $fillable = [
'question',
'values',
'type',
'inspection_id',
'order'
];
public function inspection()
{
return $this->belongsTo(Inspection::class);
}
public function answers()
{
return $this->hasMany(Answer::class);
}
}
我真的很感谢您的帮助:)
编辑:所以我遇到了一个奇怪的情况。 如果我运行以下命令:
dd($copiedManagementSystem->inspections->count();
它返回0。但是如果我运行:
dd($managementSystem->inspections->count());
它返回12,这是正确的值。
有谁知道为什么会这样吗? 如果是这样,我该如何解决该问题?
谢谢!
由于plicate()不复制关系,因此您可以尝试这样的操作。
$copiedManagementSystem = $managementSystem->replicate()
foreach($managementSystem->inspections as $inspection) {
$copiedManagementSystem->inspections->attach($inspection->replicate())
}
这是伪代码,如果您希望链接的原始检查删除$ inspection-> replicate()调用,而只需使用$ inspection
$ managementSystem可能具有的任何其他关系也是如此。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.