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

Auto Increment/Generated Id after Insert with PHQL

Hi.

I'm currently working with a project that can store the same data on Oracle or MySQL DBs. I'm using PHQL to store the data (not models). On MySQL I use autoincrement for IDs, on Oracle, triggers that read sequences and assign the values. How can I get this values after query->execute(...) ? Is there a better way to do this on Oracle?

Any help would be greatly appreciated.

Thanks.



3.6k
Accepted
answer

I'm such an idiot. I swear I read the docs searching for this and couldn't find it. And then I saw this:

$phql = "INSERT INTO Robots (name, type, year) VALUES (:name:, :type:, :year:)";

$status = $app->modelsManager->executeQuery($phql, array(
    'name' => $robot->name,
    'type' => $robot->type,
    'year' => $robot->year
));

// Create a response
$response = new Response();

// Check if the insertion was successful
if ($status->success() == true) {

    // Change the HTTP status
    $response->setStatusCode(201, "Created");

    $robot->id = $status->getModel()->id;

so, yeah, Its [response]->getModel()->[idfield].

Anyway, Thought I'd respond this in case anyone was searching for this in the future.

By the by, If you can use models (unlike me) It's even easier:

$robot->save();

echo "The generated id is: ", $robot->id;

Phalcon automatically fills the id field after calling the method save.