[Dbix-class] Passing values to a custom join condition

Lianna Eeftinck liannaee at gmail.com
Tue Jan 7 00:24:20 GMT 2014


I would do something like this, assuming you're looking for a left join:

Result/Task.pm:
__PACKAGE__->has_many(
     "site_tasks", "Lenio::Schema::Result::SiteTask",
     { 'foreign.task_id' => 'self.id' },
     { join_type => 'left', cascade_copy => 0, cascade_delete => 0 },
);

ResultSet/SiteTask.pm:
sub by_site_id {
     my ( $self, $site_id ) = @_;

     my $me = $self->current_source_alias;
     return $self->search_rs(
         { "$me.site_id" => $site_id },
     );
}

Then you can call this as:
my $site_task_rs = $schema->resultset('Task')->site_tasks->by_site_id( 
101 );

This should do the same as:
my $site_task_rs = $schema->resultset('Task')->search(
     { 'site_task.site_id' => 101 },
     { join => 'site_task' }, # or prefetch rather than join
);

(All from memory, so might have made a mistake somewhere)

ResultSet chaining is quite powerful, and used properly it can avoid 
much of the
hacking you need to do with relationships to do things like this (having 
a sane
schema also helps a lot).

I don't like the view approach, too much SQL hardcoding ... sometimes 
still a good
solution though.

Hope this helps,
Lianna



More information about the DBIx-Class mailing list