我使用Laravel 5.7,我想复制一个模型及其所有关系。
我使用以下代码:
$selection = json_decode($request->get('selection'));
$products = Product::find($selection);
foreach ($products as $product) {
// copy attributes
$new = $product->replicate();
// save model before you recreate relations (so it has an id)
$new->name = $product->name .' - new';
$new->push();
// copy relations - it works for this one
foreach($product->typeProductsTags as $typeProductTag) {
$new->typeProductsTags()->attach($typeProductTag);
}
// promotions is an array of model
$promotions = $product->promotions;
if ($promotions) {
// it erases promotions of product with the ID of the new model
$new->promotions()->saveMany($promotions);
}
}
它适用于belongsToMany关系,但是对于$promotions
,它仅擦除现有关系的外键,用新的ID替换当前的产品ID。
$product->promotions
是hasMany()
关系。
如何在不失去原始关系的情况下复制这种关系?
编辑
好吧,看来您必须复制所有关系,此代码有效:
// save promotions
$promotions = $product->promotions;
if ($promotions) {
$promotionsNew = [];
foreach ($promotions as $promotion) {
$promotionNew = $promotion->replicate();
$promotionNew->save();
$promotionsNew []= $promotionNew;
}
$new->promotions()->saveMany($promotionsNew);
}