我正在尝试通过复制具有适当关系的对象来解决问题。我通常使用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();
以下是具有检查关系的ManagementSystem模型
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,这是正确的值。
有谁知道为什么会这样?如果是这样,我该如何解决这个问题呢?
谢谢!
答案 0 :(得分:0)
由于replicate()不会复制关系,你可以尝试这样的事情。
$copiedManagementSystem = $managementSystem->replicate()
foreach($managementSystem->inspections as $inspection) {
$copiedManagementSystem->inspections->attach($inspection->replicate())
}
这是伪代码,如果您希望链接的原始检查删除$ inspection-> replicate()调用并只使用$ inspection
$ managementSystem可能具有的任何其他关系也是如此。