I really think it's a very manual process what you try to do and I even wonder (without knowing the details of the project) if the database structure could have been designed differently, in any case Laravel does not offer any direct way to regenerate these relationships when copying.
A different way and a little more "Laravel" to copy the models would be with the method replicate()
, and with dissociate()
and associate()
to join it to the new team, I think something like this (without testing):
$datos_partes = Partes::select(array('nombre', 'id_equipos', 'id_padre', 'status'))
->where('id_equipos', '=', $req->id)
->get();
foreach($datos_partes as $parte) {
$nuevaParte = $parte->replicate();
// $result en este caso contiene el modelo de Equipo
// asumo que la relación se llama equipo
$nuevaParte->equipo()->associate($result);
$nuevaParte->push();
}
So what you are doing now, in terms of reassociating it with the new "father", would look for how to generate a temporary arrangement where you "map" old and new parents:
$nuevosIds = [];
foreach ($datos_partes as $parte) {
$nuevaParte = $parte->replicate();
$nuevaParte->equipo()->associate($result);
$nuevaParte->save();
// pueden haber errores aquí, pero entiendes la idea
$nuevosIds[$parte->id] = $nuevaParte->id;
if (isset($nuevosIds[$nuevaParte->id_padre])) {
// reasociar al modelo correspondiente
$nuevoPadre = Partes::find($nuevosIds[$nuevaParte->id_padre]);
// asumiendo que la relación con si mismo se llame padre
$nuevaParte->padre()->associate($nuevoPadre);
$nuevaParte->save();
// si lo anterior no funciona lo puedes hacer manual
// $nuevaParte->id_padre = $nuevosIds[$nuevaParte->id_padre];
}
}