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:
- product hasMany product_options
- product belongsToMany category (trough product_categories)
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).