[Dbix-class] many_to_many and shortcut methods

Jess Robinson castaway at desert-island.me.uk
Wed Jan 9 14:30:12 GMT 2008



On Wed, 9 Jan 2008, Sven Eppler wrote:

> Hello!

Hi,

Please don't start new threads by replying to existing ones. People with 
sane email clients will get all messed up..

> I currently work on getting my emails into a database. Therefore i have
> following table setup:
>
> Mails: id, body, received
> MailsToHeaders: mailid, headerid, value
> Headers: id, name
>
> I have a many_to_many relationship established between the table Mails and
> Headers over the linking table MailsToHeaders. No Problem sofar.
>
> But what i currently want to do, is adding some shortcut methods to the
> Mail-Results to simply do something like this:
>
> my @mails = $schema->resultset("Mails")->search(undef, { prefetch => {
> "mails_to_headers" => "headerid" });
>
> # the prefetching returns all headers and their values to the
> corresponding mail
> foreach my $mail (@mails) {
>        print $mail->to; // Return the value of the header with the name "To"
>        print $mail->subject; // Return the value of the header with the
> name "Subject"
> }

So edit your Mails.pm file, and add a method that does it?

Something like:

  sub subject {
   my ($self) = @_;

   return $self->mails_to_headers->headerid->subject;

}

## Or use whatever your m2m bridge is called, rather than the extra calls, 
but it's really all the same.

> I tried to play around with search_related. But this always executes an
> new Query, what is not really needed (but i understand that DBIx::Class
> may not be able to recognise this :) )

You didn;t say how you tried, so can't help there.

> The only thing i'm currently thinking about is to iterate internaly in
> these methods over my results und return the corresponding resultset. But
> that doesn't look like a good solution to me.
>

Jess



More information about the DBIx-Class mailing list