X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=blobdiff_plain;f=lib%2FDBIx%2FClass%2FManual%2FCookbook.pod;h=4dec7ae72222c668ccc677e268fc39982b3e512a;hb=4aeeed8aba0096f1272b29d9dc794714201f232c;hp=65f802d8ddae0213602bd9a4b97ba982fe44281a;hpb=acee4e4d60a59d831571937ce4148cd4ffd5ac80;p=dbsrgits%2FDBIx-Class-Historic.git diff --git a/lib/DBIx/Class/Manual/Cookbook.pod b/lib/DBIx/Class/Manual/Cookbook.pod index 65f802d..4dec7ae 100644 --- a/lib/DBIx/Class/Manual/Cookbook.pod +++ b/lib/DBIx/Class/Manual/Cookbook.pod @@ -72,8 +72,10 @@ L. =head3 Using specific columns -When you only want selected columns from a table, you can use C to -specify which ones you need: +When you only want specific columns from a table, you can use +C to specify which ones you need. This is useful to avoid +loading columns with large amounts of data that you aren't about to +use anyway: my $rs = $schema->resultset('Artist')->search( undef, @@ -85,6 +87,9 @@ specify which ones you need: # Equivalent SQL: # SELECT artist.name FROM artist +This is a shortcut for C and C. + =head3 Using database functions or stored procedures The combination of C attribute of C to force ordering). + +=head2 Want to know if find_or_create found or created a row? + +Just use C instead, then check C: + + my $obj = $rs->find_or_new({ blah => 'blarg' }); + unless ($obj->in_storage) { + $obj->insert; + # do whatever else you wanted if it was a new row + } + +=head3 Wrapping/overloading a column accessor + +Problem: Say you have a table "Camera" and want to associate a description +with each camera. For most cameras, you'll be able to generate the description from +the other columns. However, in a few special cases you may want to associate a +custom description with a camera. + +Solution: + +In your database schema, define a description field in the "Camera" table that +can contain text and null values. + +In DBIC, we'll overload the column accessor to provide a sane default if no +custom description is defined. The accessor will either return or generate the +description, depending on whether the field is null or not. + +First, in your "Camera" schema class, define the description field as follows: + + __PACKAGE__->add_columns(description => { accessor => '_description' }); + +Next, we'll define the accessor-wrapper subroutine: + + sub description { + my $self = shift; + + # If there is an update to the column, we'll let the original accessor + # deal with it. + return $self->_description(@_) if @_; + + # Fetch the column value. + my $description = $self->_description; + + # If there's something in the description field, then just return that. + return $description if defined $description && length $descripton; + + # Otherwise, generate a description. + return $self->generate_description; + } + =cut