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

MVC - lastInsertId

Do you plan any changes in MVC where you forward table name to lastInsertId function? Currently when you dont use sequence tables the sequenceName param is null which is described on https://github.com/phalcon/cphalcon/blob/bf9da26e6e20ea05dd69881b9cd0c2536ec53bcb/ext/mvc/model.c#L3596. It would be really great assign table value to sequence_name variable because latest version of MSSQL returns null for SCOPE_IDENTITY query and only function which certainly works needs tableName or is there any different way how I can read table name from adapter?

Edit 1: It almost looks like Phalcon close connection to DB immediately after query or something like that because I get null when I insert new value. However when I test same insert query in SQL Management Studio, everything works well.

hi , which kind of data models to use for model layer? (orm, phql, etc...)

Mostly ORM. Current version of my drivers lastInsertId functions looks like this:

public function lastInsertId($sequenceName = null)
{
    if (empty($sequenceName)) {
        $sql = 'SELECT SCOPE_IDENTITY() as LastIdentity';
    } else {
        $sql = "SELECT IDENT_CURRENT('" . $sequenceName . "') as LastIdentity";
    }

    $record = $this->fetchOne($sql);
    return (int)$record['LastIdentity'];
}

After save i simply check If primaryKey > 0:

if ($model->save()) {

    $insertedId = $model->$primaryKey;
    if (!$insertedId) {
        //hotfix - not sure if this work on production
        $insertedId = $model->getWriteConnection()->lastInsertId($model->getSource());
    }
}

if data model obj is $model you can handel inserted id with $model->id;

Are you sure with $model->id when id property does not exists? Ive defined primary key in model class. However after $model->save() the primary key is empty because function lastInsertId returns null. Thats why I check if primaryKey has positive number and if isnt I will call lastInsertId again with tableName. Dont forget i use MSSQL adapter and driver and I use MSSQL Server 2012 or Microsoft Azure SQL.