I have a problem with replicating one of my models with all the relationships.
The database structure is as follows:
Table1: products
id
name
Table2: product_options
id
product_id
option
Table3: categories
id
name
Pivot table: product_categories
product_id
category_id
Relationships are:
I would like to clone a product with all the relationships. Currently here is my code:
$product = Product::with('options')->find($id);
$new_product = $product->replicate();
$new_product->push();
foreach($product->options as $option){
$new_option = $option->replicate();
$new_option->product_id = $new_product->id;
$new_option->push();
}
But this does not works (the relationships are not cloned - currently I just tried to clone the product_options).
Laravel provides a very handy function for this called replicate which will take an Eloquent model and make a copy so you can then make changes and save it. Here's an example of how you might use this. Let's pretend you have a blog post and you want to make a copy of it to publish again.
Laravel includes Eloquent, an object-relational mapper (ORM) that makes it enjoyable to interact with your database.
If you want, you can use Eloquent without Laravel. Actually, Laravel is not a monolithic framework.
Eloquent ORM is best suited working with fewer data in a particular table. On the other side, query builder takes less time to handle numerous data whether in one or more tables faster than Eloquent ORM. In my case, I use ELoquent ORM in an application with tables that will hold less than 17500 entries.
This code, worked for me:
$model = User::find($id);
$model->load('invoices');
$newModel = $model->replicate();
$newModel->push();
foreach($model->getRelations() as $relation => $items){
foreach($items as $item){
unset($item->id);
$newModel->{$relation}()->create($item->toArray());
}
}
Answer from here: Clone an Eloquent object including all relationships?
This answer (same question), also works fine too.
//copy attributes from original model
$newRecord = $original->replicate();
// Reset any fields needed to connect to another parent, etc
$newRecord->some_id = $otherParent->id;
//save model before you recreate relations (so it has an id)
$newRecord->push();
//reset relations on EXISTING MODEL (this way you can control which ones will be loaded
$original->relations = [];
//load relations on EXISTING MODEL
$original->load('somerelationship', 'anotherrelationship');
//re-sync the child relationships
$relations = $original->getRelations();
foreach ($relations as $relation) {
foreach ($relation as $relationRecord) {
$newRelationship = $relationRecord->replicate();
$newRelationship->some_parent_id = $newRecord->id;
$newRelationship->push();
}
}
From here: Clone an Eloquent object including all relationships?
The code works fine for many to many relationships in my experience.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With