Auto-Increment and Sequences

Auto-Increment

You can ge the most-recent auto-increment value from the SQL connection using Solar_Sql_Adapter::lastInsertId().

<?php
$sql = Solar::factory('Solar_Sql');
$sql->query("INSERT INTO table_name (id, ...) VALUES (null, ...)";
$id = $sql->lastInsertId();
?>

Sequences

Solar_Sql also has portable support for sequences. Using a sequence is as easy as calling Solar_Sql_Adapter::nextSequence() with a sequence name of your choosing. In general, it's easiest to name the sequence after a table and column.

With auto-increment, you get the last insert ID after the insert. With sequences, you get the sequence value before the query, then you use it in the insert statement.

<?php
$sql = Solar::factory('Solar_Sql');
$id = $sql->nextSequence('table_name__id');
$sql->query("INSERT INTO table_name (id, ...) VALUES ($id, ...)");
?>

The Solar_Sql_Adapter::nextSequence() method creates the sequence on-the-fly and returns the next value for you. You can create and drop sequences on your own with Solar_Sql_Adapter::createSequence() and Solar_Sql_Adapter::dropSequence(), respectively.

 
manual/sql_basics/increment_and_sequence.txt · Last modified: 2008/08/25 08:48 (external edit)