We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Error get lastInsertId in Try catch

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 in a try catch?

<?php 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

        }

You have method id() here. It should just property. Also you should in your database have column id with PRIMARY key?

If Mr. the table has an id as a primary key, it is called id_variation_last_month. this is the model

<?php

class VariationsLastMonth extends \Phalcon\Mvc\Model {

/**
 *
 * @var integer
 * @Primary
 * @Identity
 * @Column(type="integer", length=11, nullable=false)
 */
protected $id_variation_last_month;

/**
 * Method to set the value of field id_variation_last_month
 *
 * @param integer $id_variation_last_month
 * @return $this
 */
public function setIdVariationLastMonth($id_variation_last_month)
{
    $this->id_variation_last_month = $id_variation_last_month;

    return $this;
}

/**
 * Returns the value of field id_variation_last_month
 *
 * @return integer
 */
public function getIdVariationLastMonth()
{
    return $this->id_variation_last_month;
}

/**
 * Initialize method for model.
 */
public function initialize()
{
    $this->setSchema("sieg");
    $this->setSource("variations_last_month");
    $this->hasMany('id_variation_last_month', 'DetailsBalance', 'id_variation_last_month', ['alias' => 'DetailsBalance']);
}

You have method id() here. It should just property. Also you should in your database have column id with PRIMARY key?



145.0k
Accepted
answer

Then you need to use getIdVariationLastMonth() method.