Getting hold of newly created objects
[prev]
[thread]
[next]
[Date index for 2005/07/01]
I'm wondering if I've got the wrong end of the stick here and I'm just
being stupid. I need to create new objects and then work with them.
After creating the object, CDBI throws away all the object's data. The
primary key is an auto-increment column in MySQL - and the newly created
object does not include its primary key value. So there's no way to
retrieve the object from the db, or to get it to populate its column
values.
So here's a method I use to create and return new objects. Am I missing
something? Or would this make a useful patch for CDBI?
# If pk values are created in the database (e.g. in a MySQL AUTO_INCREMENT
# column), then they will not be available in the new object. Neither will
# anything else, because CDBI discards all data before returning the new
# object.
sub _create_object
{
my ( $me, $class, $data ) = @_;
die "_create_object needs a CDBI class, not an object" if ref( $class );
my $obj = $class->create( $data );
my @pcs = map { $obj->get( $_ ) } $obj->primary_columns;
my $ok;
$ok &&= $_ for @pcs;
return $obj if $ok; # every primary column has a value
die "No pks for new object $obj" unless @pcs == 1; # 1 undef value -
we can find it
# this works for MySQL and SQLite - these may be the only dbs that
don't
# supply the pk data in the first place?
my $id = $obj->_auto_increment_value;
return $class->retrieve( $id ) || die "Could not retrieve newly
created '$obj' object with ID '$id'";
}
Thanks,
d.
|
Getting hold of newly created objects
David Baird 11:19 on 01 Jul 2005
|