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

how get ID from model->create()

has not found in documentation how get ID record after add it in table

that on similar

function id(){ return mysqli_insert_id($this->conect); }

in

$user = new Users();
$user->password = 'pass';
$user->name = 'user';

if ($user->create())
{
    $id = $user->id(); // ????? how ????
}

You can get it from the connection object like this:

$result = $user->create(); 
if ($result) {
    $id = $user->getConnection()->lastInsertId(); 
}


98.9k
Accepted
answer

If the field 'id' is auto_increment you can automatically get the generated value by just accessing the property after saving:

if ($robot->save()) {
    echo "The robot id is", $robot->id, '<br>';
}


17.0k

thank you for answer

edited Oct '14

Thank you so much! Very clear and legible :D

smooth and easy as it intended to be in Phalcon

If the field 'id' is auto_increment you can automatically get the generated value by just accessing the property after saving:

if ($robot->save()) {
   echo "The robot id is", $robot->id, '<br>';
}

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>';
}