php - How I can save data in two tables simultaneously in laravel? -
i have following data mode l
detalle_servicio
has many material_usado
, material_usado
belongs detalle_servicio
when save values in material_usado should know id detelle_servido, can not that. have following code
route
route::post('/upload', function(){ $path = public_path().'/servicios'; try{ $upload_success1 = input::file('foto1')->move($path,'1'); $upload_success2 = input::file('foto2')->move($path,'2'); $upload_success3 = input::file('foto3')->move($path,'3'); $upload_success4 = input::file('foto4')->move($path,'4'); }catch(exception $e) { $e->getmessage(); } $input = input::get('json'); $json = json_decode($input); if($upload_success1 && $upload_success2 && $upload_success3 && $upload_success4) { //db::insert("insert detalle_servicio (rutafoto1, rutafoto2, rutafoto3, rutafoto4, fechatermino, latitud, longitud, servicio_idservicio) values(?,?,?,?,?,?,?,?)", array($path.'1', $path.'2', $path.'3', $path.'4',$json->termino, $json->latitud, $json->longitud, $json->idservicio)); $entradas = array( 'rutafoto1' => $path.'1', 'rutafoto2' => $path.'2', 'rutafoto3' => $path.'3', 'rutafoto4' => $path.'4', 'fechatermino' => $json->termino, 'latitud' => $json->latitud, 'longitud' => $json->longitud, 'servicio_idservicio' => $json->idservicio ); detalle_servicio::create($entradas); $array = array('code' => '202', 'message' => 'done'); return response::json($array); } else { $array = array('code'); return response::json('error', 400); } });
you can see json containing values that store in database
i keep data in database of detalle_servicio
table need save data in material _usado
need id generated when save data in table detalle_servicio
model
class detalle_servicio extends eloquent{ protected $table = 'detalle_servicio'; protected $primarykey = 'iddetalle_servicio'; protected $fillable = array('rutafoto1', 'rutafoto2', 'rutafoto3', 'rutafoto4', 'fechatermino', 'latitud', 'longitud', 'servicio_idservicio'); public function servicio(){ return $this->belongsto('servicio', 'idservicio'); //le pertenece } public function material_usado(){ return $this->hasmany('material_usado', 'idmaterial_usado'); } }
and
class material_usado extends eloquent{ protected $table = 'material_usado'; protected $primarykey = 'idmaterial_usado'; public function detalleservicio(){ return $this->belongsto('detalle_servicio', 'iddetalle_servicio'); } }
how can it?
when use this:
detalle_servicio::create($entradas);
it returns model instance created should way:
$detalle_servicio = detalle_servicio::create($entradas);
now can id of created model using:
$detalle_servicio->id;
so, may this:
if($detalle_servicio = detalle_servicio::create($entradas)) { $id = $detalle_servicio->id; // ... }
Comments
Post a Comment