我已经尝试了一些在网上搜索过的东西,但仍然没有成功,以前版本的 Laravel 有很多内容,但对于 8 我还没有找到。
我尝试这样做,但没有成功。
public function DuplicateList($idList)
{
$getList = Accompaniment::with(['categoryAccompaniments', 'categoryAccompaniments.additionals'])->find($idList);
$newList = $getList->replicate();
$newList->push();
foreach($getList->categoryAccompaniments as $categoryAccompaniment)
{
$newList->categoryAccompaniments()->attach($categoryAccompaniment);
}
}
这就是在 Laravel 8 中复制 1 条记录与所有关系的方法
public function DuplicateList($idList)
{
$getList = Accompaniment::with(['categoryAccompaniments', 'categoryAccompaniments.additionals'])->find($idList);
$newList = $getList->replicate();
$newList->save();
$getCategories = $getList->categoryAccompaniments->toArray();
$newList->categoryAccompaniments()->createMany($getCategories);
}
请为关系添加受保护的属性
categoryAccompaniments
模型的类
protected $guarded = ['id'];
如果 没有,您可能会收到
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry for key 'PRIMARY'
as id 在大多数情况下将是主键且唯一。