[CDBI] Making Class::DBI objects from a search_ method result?

Matt S Trout dbix-class at trout.me.uk
Mon Oct 24 15:34:45 BST 2005

On Mon, Oct 24, 2005 at 03:13:43PM +0100, Steven Mackenzie wrote:
> Hello,
> I would like to add a convenience method to once of my Class::DBI
> objects, so that I can get a collection of related CDBI instance objects
> via a JOIN, rather than by following has_many relations.
> >From looking at the doc
> http://search.cpan.org/dist/Class-DBI/lib/Class/DBI.pm#has_a
> and
> http://cdbi.dcmanaged.com/wiki/Beginners_guide#Entity_Relationship_Diagram_.28ERD.29
> I think something like this should be possible:
>  # add a sub to get all persons in the band that created a CD; assumes
>  # that the current CD was created by a band!
>  CD->set_sql
>   ( persons =>
>     qq{
>         SELECT p.*
>         FROM CD cd
>           JOIN artist a on cd.artistid = a.artistid
>           JOIN artistgroup ag on a.artistid = ag.bandartistid
>           JOIN person p on ag.personartistid = p.artistid
>         WHERE cd = $self.cdid
>       }
>   );
>   # ... elsewhere ...
>   my @persons = $cd->search_persons();
> The array @persons is now an array of hashes.  I'd rather it was an
> array of PERSON rows though. Is there a nice way to do that?

use base qw/Class::DBI::Sweet/;

my @persons = Person->search({ 'artistgroup.artist.cd' => $cd });

unless you've got a many-many in the middle of there, in which case you
probably want to fetch the many-many table and prefetch the person objects.

     Matt S Trout       Specialists in Perl consulting, web development, and
  Technical Director    UNIX/Linux systems architecture and automation. Mail
Shadowcat Systems Ltd.  mst (at) shadowcatsystems.co.uk for more information

 + Help us build a better perl ORM: http://dbix-class.shadowcatsystems.co.uk/ +

More information about the ClassDBI mailing list