Hi, I have a problem getting the last id of a related table. if I use $ variation-> id; it brings me null and if I use $ variation-> theInsertId (); I get an error with foreign key problems
Can you get the last id after a save within a try catch?
try{
///////Iniciar bloque de transacción/////////////////////////
$this->db->begin();
if (count($prev_month_balance) > 0) {
$variation = new VariationsLastMonth();
$variation->setMonthPrev($prev_month_balance[0]->getRate());
$variation->setMonthCurrent($rate_);
$variation->setYear(date("Y"));
$variation->setState(1);
if ($variation->save()){
$lastId = $variation->id();
}else{
throw new Exception("¡ERROR: al inserta en la bd!", 1);
}
}
$month_current = date("m");
$year_current = date("Y");
$detailBalance = DetailsBalance::query()
->where("id_bank = :id_bank:")
->andWhere("id_sub_product = :id_sub_product:")
->andWhere("id_concept = :id_concept:")
->andWhere("year = :year:")
->andWhere("id_month = :month:")
->bind(["id_bank" => $id_bank, "id_sub_product" => $id_sub_product, "id_concept" => $id_concept, "month" => $month_current, "year" => $year_current])
->execute();
if (count($detailBalance) > 0) {
// Validamos si existe el sub producto + banco + registrado
$this->response->setJsonContent(array(
"subProduct_repeat" => true
));
return $this->response->send(); // aqui se envia la respuesta ajax de nuevo a la vista
}
$rate = new DetailsBalance();
$rate->setIdBank(intval($id_bank));
$rate->setIdSubProduct(intval($id_sub_product));
$rate->setIdConcept(intval($id_concept));
$rate->setRate($rate_);
$rate->setYear(intval(date("Y")));
$rate->setIdMonth(intval(date("m")));
$rate->setIdVariationLastMonth($lastId);
$rate->setState(1);
//mostrando mensajes de error de insercion en bd
if (!$rate->save()){
throw new Exception("¡ERROR: al inserta en la bd!", 2);
}
///////Finalizar bloque de transacción y guardar/////////////
$this->db->commit();
}catch(\Exception $e){
///////Deshacer cambios hechos en el/////////
///////bloque de transaccion respestivo//////
$this->db->rollback();
$this->response->setJsonContent(array(
"error_registro" => $e->getMessage()
));
$this->response->setStatusCode(200, "OK"); //la peticion ha sido realizada con exito
return $this->response->send(); // aqui se envia la respuesta ajax de nuevo a la vista
}
If the field 'id' is auto_increment you can automatically get the generated value by just accessing the property after saving:
```php
if ($robot->save()) {
echo "The robot id is", $robot->id, '<br>';
}