I said above "it should be possible to do e.g. $painting->artist, but I think that could be solved with the existing DB schema using some more advanced DBIx features".
You can add missing pseudo-relationships very easily by turning your ResultSet class into a Moo class and adding object methods. For this demonstration, add the following code to Painting.pm, Play.pm and Poem.pm (after the "do not add anything above this line" line!):
... and add the following to Artist.pm and Comment.pm:use Moo; sub artist { $_[0]->artwork->artist } # returns a DBIx obj sub artist_name { $_[0]->artwork->artist->name } # returns a string sub name { $_[0]->artwork->name } # returns a string
use Moo; sub language { $_[0]->country->language->name } # string
Now in order to get "Poems not by English artists that tobyink doesn't hate", the query code remains unchanged (because the new accessors are DBIx-side, not SQL-side):
$rs = $db->resultset('Poem')->search({ 'user.name' => 'tobyink', 'comments.text' => { '!=' => 'bad' }, # DBIx handles this NOT 'country.name' => \'!= country_2.name' # literal SQL for this NOT }, { prefetch => { artwork => [ { artist => 'country' }, { comments => { user => 'country' } }, ], # table aliased here to 'country_2 +' }, });
But the application code changes from:
... to:while ( my $poem = $rs->next ) { say sprintf(q{tobyink doesn't hate "%s" (%s)}, $poem->artwork->name, $poem->artwork->artist->name, ); }
while ( my $poem = $rs->next ) { say sprintf(q{tobyink doesn't hate "%s" (%s)}, $poem->name, $poem->artist_name, ); }
You can use the new accessors throughout the application, e.g. for making a comparison similar to the one in "Comments by Users who speak the same Language as the Artist" in application code rather than SQL:
if ( $comment->language eq $play->artist->language ) { ... }
And you can add arbitrary methods to the classes, not just accessors. For example, if you are building a REST application where your DB tables and ORM classes represent resources exposed via API endpoints, you can add a custom chained deletion flow, or a standard method that builds the HTTP response object:
... so you can always call $obj->endpoint_data when you are finished processing the logic for the request.use Moo; sub endpoint_data { return { map { $_ => $_[0]->$_ } qw/only these fields/ }; }
Hope this helps!
In reply to Re: DBIx::Class and "complex" joins (was Re^4: DB: what kind of relationship?)
by 1nickt
in thread DB: what kind of relationship?
by bliako
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |