Re: [CDBI] How to sort "has_many" relation after I've declared it?
paul trader <fliptop-9C0dvrXKiPZWk0Htik3J/[email protected]> Tue, 21 Aug 2012 12:42:48 -0400 (EDT)
| Newsgroups | gmane.comp.lang.perl.modules.class-dbi |
|---|---|
| Message-ID | <[email protected]> |
On Tue, 21 Aug 2012 at 10:35, David McMath opined:
DM:I looked at Class::DBI::Sweet as well. I don't have the guts to change
DM:my base class today but it looks a bit more promising
hi david - i've read through your solution and am wondering, have you
looked at using class::dbi::abstractsearch?
it's not quite as elegant as passing an 'order_by' clause when calling a
has_many relationship, but in those instances where you may want to sort
results of the same relationship differently, it works nicely.
instead of:
__PACKAGE__->has_many(tracks => Music::Cd::Track, { order_by =>
'track_num' });
...and later...
my @tracks = $cd->tracks;
you can do this using c::dbi::abstractsearch:
use Class::DBI::AbstractSearch;
...
__PACKAGE__->has_many(tracks => Music::Cd::Track);
...and later...
my @tracks = Music::Cd::Track->search_where(
{ cd => $cd->id },
{ order_by => 'track_num ASC' }
);
# or maybe you want the tracks alphabetically:
my @tracks = Music::Cd::Track->search_where(
{ cd => $cd->id },
{ order_by => 'title ASC' }
);
as i said, it's not quite as elegant, but it does work.
c::dbi::abstractsearch also includes methods for using limit/offset which
is very handy as well. it's a very useful extension to c::dbi.
regards, paul