[Catalyst] Custom fields in a model

Matija Grabnar matija at serverflow.com
Wed Jan 21 18:41:35 GMT 2009


Greg Coates wrote:
> I have a database table -- let's call it 'Contacts' that I'm accessing 
> through a DBIx::Class model.  This table has two fields called 
> 'first_name' and 'last_name'.
>
> Could I get some suggestion on the best way to add code to the model 
> (or the schema) to allow me to add a custom field to the resultset 
> without having an actual column in the database table?  I want to be 
> able to access a field in the resultset called something like 
> 'common_name'. This field would contain a concatenation of the first 
> and last name fields for people and only the data from the last name 
> for other entities like businesses.
At the end of the schema definition file (if you're generating schema, 
it's after the DO NOT MODIFY THIS OR ANYTHING ABOVE! line)
 add the following:


__PACKAGE__->resultset_class('Contacts::ResultSet');

package Contacts::ResultSet;
use warnings;
use strict;
use base 'DBIx::Class::ResultSet';

sub common_name {
    if ($self->person) {
      return $self->first_name." ".$self->last_name;
    } else {
    # .... etc.....
}



More information about the Catalyst mailing list