[CDBI] has_many limiting the search.

Cees Hek ceeshek at gmail.com
Sun Dec 10 23:01:00 GMT 2006

On 12/10/06, Praveen Hombaiah <phombaiah at gmail.com> wrote:
> In a given class, while defining a has_many relationship, is it possible to
> setup a search criterion,
> for instance.
> while defining the following relationship, is there a way to limit the CDs
> that are returned, lets say we want to return only CDs that are "in_stock".
> Music::Artist->has_many(cds => 'Music::CD');

If you are using version 3.06 or greater, then you can add a
constraint to the has_many:

Music::Artist->has_many(cds_in_stock => 'Music::CD', { constraint => {
in_stock => 'Y' } } );

By naming it cds_in_stock, you can still have to original relationship
in place as well:

Music::Artist->has_many(cds => 'Music::CD');

The cds_in_stock method works the same as any other has_many method.
The following two statements would be equivalent:

my @cds = $artist->cds_in_stock(year => 1980);
my @cds = $artist->cds(year => 1980, in_stock => 'Y');

add_to_cds_in_stock will also DWIM, and automatically add the in_stock
=> 'Y' parameter to any nre CDs being created, so the following are
equivalent as well:

my $cd = $artist->add_to_cds_in_stock({
    title  => 'October',
    year   => 1980,
my $cd = $artist->add_to_cds({
    title  => 'October',
    year   => 1980,
    in_stock => 'Y',


Cees Hek

More information about the ClassDBI mailing list