[Dbix-class] Using joins and aggregate functions with DBIC
Nilson Santos Figueiredo Junior
acid06 at gmail.com
Fri Jun 2 15:27:11 CEST 2006
On 5/26/06, Matt S Trout <dbix-class at trout.me.uk> wrote:
> > sub search {
> > my ($self, $cond, $attrs) = @_;
> my $alias = $self->{attrs}{alias}
> > $self->next::method($cond, $attrs)->next::method(
> > {},
> > {
> > join => [qw/logs/],
> select => [(map {"${alias}.${_}"}
> > $self->result_source->columns), {sum => 'logs.hours_spent'} ],
> > as => [$self->result_source->columns, qw/hours_spent/],
> group_by => [ "${alias}.id" ]
> > }
> > );
> > }
This sort of worked. However, it didn't perfectly DWIM.
When I use the relationship accessors ($user->tasks), I expected it to
sum only the specific user task logs. Instead, it summed everything
up.
There's another problem, take a look at the query produced:
SELECT
task.id,
task.project_id,
task.date,
task.description,
task.is_closed,
task.comments,
SUM( logs.hours_spent )
FROM task_user me
JOIN task task
ON ( task.id = me.task_id )
LEFT JOIN task_log logs ON ( logs.task_id = task.id )
LEFT JOIN task_log logs_2 ON ( logs_2.task_id = task.id )
WHERE ( ( ( ( ( me.user_id = ? ) ) ) ) ) GROUP BY task.id;
Why there are two references to task_log when only of them is used? I
called $user->tasks without any additional parameters so I can't
imagine where this came from.
When I search() without using the relationship accessor magic (i.e.
$model->search), this duplication does not occur. Might this be a bug?
-Nilson Santos F. Jr.
More information about the Dbix-class
mailing list