CodeIgniter Forums
After save datamapper object, how do I get id - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Libraries & Helpers (https://forum.codeigniter.com/forumdisplay.php?fid=22)
+--- Thread: After save datamapper object, how do I get id (/showthread.php?tid=44057)



After save datamapper object, how do I get id - El Forum - 08-01-2011

[eluser]RJ[/eluser]
Once we run the $object->save() method how do we retrieve the ID this object was saved with?

thanks


After save datamapper object, how do I get id - El Forum - 08-01-2011

[eluser]IgnitedCoder[/eluser]
This works for me.

Code:
$object = new $obj();
$object->save_as_new();
//or
//using save implies an update so you generally want to already have an id assigned.
$object->id = 10;
$object->save(); //adds new if id is not supplied, updates existing if id is assigned.

echo $object->id;



After save datamapper object, how do I get id - El Forum - 08-01-2011

[eluser]RJ[/eluser]
$object->save_as_new();
Echo $object->id; (returns NULL)

$object->save();
Echo $object->id; (returns 0)

We could explicitly set the ID but would need to know the next #.

Any thoughts?


After save datamapper object, how do I get id - El Forum - 08-01-2011

[eluser]IgnitedCoder[/eluser]
Make sure your table has an id field of type int and that its set to auto increment/primary key. Remember the table name is plural and the Model is singular.

Code:
CREATE TABLE `tests` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `thetext` varchar(200) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

Model

Code:
class Test extends DataMapper {

}

Controller

Code:
$test = new Test();
$test->thetext = 'test it';
$test->save();
echo $test->id;



After save datamapper object, how do I get id - El Forum - 08-01-2011

[eluser]RJ[/eluser]
We will check that out. Thanks Brendan