[Dbix-class] hardcoded (multicolumn) relationship (beginner)

Jason Gottshall jgottshall at capwiz.com
Mon Feb 2 21:16:57 GMT 2009


Heiko Gruner wrote:
> Hi,
> I am looking for some hints on a problem of hardcoding a relationship to 
> a multicolumn key in a different table:
> 
> My App Package is defined with a PK "appid".
> It needs to get some entries from the Maps Package,
> wheras the Maps table has a multicolumn key (fixedid and appid).
> The appid columns of both tables would match 1:1.
> But the "foreign.fixedid" needs to match '14'
> (other Schema/Applications use other values of the fixedid in Maps).
> 
> How would i hardcode this value of "14" into this relationship ?
> 
> 
> ---------------------------------
> 
> __PACKAGE__->has_many( maps => 'Project::Schema::Maps',
> { 'foreign.fixedid' => 'self.workaroundid',
>   'foreign.appid'   => 'self.appid'}, );
> 
> ---
> 
> workaround: inserted an extra column "workaroundid" with identical data 
> values ('14') for the whole App table :-(

You might try creating the relationship accessor yourself in a custom 
ResultSet class. First create a partial relationship using the 
key-to-key mapping and a bogus name:

     __PACKAGE__->has_many( map_rows => 'Project::Schema::Maps',
         { 'foreign.appid'   => 'self.appid'}, );

(The name "map_rows" isn't very good, but I couldn't think of anything 
better....) Then create a custom Project::ResultSet::App class that 
explicitly defines the methods has_many would have generated:

     sub maps {
         return shift->search_related('map_rows', { fixedid => 14 });
     }

     sub maps_rs { return shift->maps->search_rs }

Of course, you also have to create the corresponding belongs_to 
relationship in the Maps class:

     __PACKAGE__->belongs_to( app_row => 'Project::Schema::App',
         { 'foreign.appid'   => 'self.appid'}, );

Then, just for completeness, your custom Project::ResultSet::Maps should 
probably include:

     sub app {
         my $self = shift;
         return $self->fixedid == 14
             ? $self->app_row
             : undef;
         # or you could die, throw an exception, etc
     }

Somebody holler if I'm going the wrong way with this!

HTH,
Jason

-- 
Jason Gottshall
jgottshall at capwiz.com




More information about the DBIx-Class mailing list