| 1 | package Rapi::Blog::DB::ResultSet::Tag; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | |||
| 6 | use Moo; | ||
| 7 | extends 'DBIx::Class::ResultSet'; | ||
| 8 | |||
| 9 | use RapidApp::Util ':all'; | ||
| 10 | |||
| 11 | __PACKAGE__->load_components(qw(Helper::ResultSet::CorrelateRelationship)); | ||
| 12 | |||
| 13 | sub by_popularity { | ||
| 14 | my $self = shift; | ||
| 15 | |||
| 16 | $self->search_rs(undef, { | ||
| 17 | order_by => { '-desc' => $self->correlate('post_tags')->count_rs->as_query }, | ||
| 18 | }) | ||
| 19 | } | ||
| 20 | |||
| 21 | sub alphabetically { | ||
| 22 | (shift)->search_rs(undef, { order_by => { '-asc' => 'me.name' } }) | ||
| 23 | } | ||
| 24 | |||
| 25 | sub by_most_recent { | ||
| 26 | (shift)->search_rs(undef, { | ||
| 27 | join => { 'post_tags' => 'post' }, | ||
| 28 | order_by => { '-desc' => 'post.ts' }, | ||
| 29 | group_by => 'me.name' | ||
| 30 | }) | ||
| 31 | } | ||
| 32 | |||
| 33 | |||
| 34 | __PACKAGE__->load_components('+Rapi::Blog::DB::Component::ResultSet::ListAPI'); | ||
| 35 | |||
| 36 | sub _api_default_params {{ limit => 200, sort => 'popularity' }} | ||
| 37 | sub _api_param_arg_order { [qw/search post_id/] } | ||
| 38 | |||
| 39 | # Method exposed to templates: | ||
| 40 | sub list_tags { | ||
| 41 | my ($self, @args) = @_; | ||
| 42 | |||
| 43 | my $P = $self->_list_api_params(@args); | ||
| 44 | |||
| 45 | my $Rs = $self | ||
| 46 | ->search_rs(undef,{ '+columns' => { | ||
| 47 | # pre-load 'posts_count' -- the Row class will use it (see Result::Tag) | ||
| 48 | posts_count => $self->correlate('post_tags')->count_rs->as_query | ||
| 49 | }}); | ||
| 50 | |||
| 51 | $P->{sort} ||= 'popularity'; | ||
| 52 | if($P->{sort} eq 'alphabetical') { | ||
| 53 | $Rs = $Rs->alphabetically; | ||
| 54 | } | ||
| 55 | elsif($P->{sort} eq 'recent') { | ||
| 56 | $Rs = $Rs->by_most_recent; | ||
| 57 | } | ||
| 58 | else { | ||
| 59 | $Rs = $Rs->by_popularity | ||
| 60 | } | ||
| 61 | |||
| 62 | $Rs = $Rs->search_rs( | ||
| 63 | { 'post_tags.post_id' => $P->{post_id} }, | ||
| 64 | { join => 'post_tags' } | ||
| 65 | ) if ($P->{post_id}); | ||
| 66 | |||
| 67 | $Rs = $Rs->search_rs( | ||
| 68 | { 'me.name' => { like => join('','%',$P->{search},'%') } } | ||
| 69 | ) if ($P->{search}); | ||
| 70 | |||
| 71 | return $Rs->_list_api; | ||
| 72 | } | ||
| 73 | |||
| 74 | |||
| 75 | 1; |