Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: how to express HAVING COUNT in eloquent

Tags:

sql

php

laravel

How can I express this query in Laravel?

SELECT `projects_issues`.* FROM `projects_issues` 

 JOIN `projects_issues_tags` 
    ON `projects_issues_tags`.`issue_id` = `projects_issues`.`id` 

 JOIN `tags` 
    ON (`tags`.`id`  = `projects_issues_tags`.`tag_id`) 

WHERE `project_id` = '1' 
AND `tags`.`tag` IN('tagname1','tagname2')

GROUP BY `projects_issues`.`id` 
HAVING COUNT(DISTINCT `tags`.`tag`) = 2

ORDER BY `projects_issues`.`updated_at` DESC

Right now my code is this. `

$issues = \Project\Issue::with('tags');

        if ($tags || $sort_by != 'updated')
        {
            $issues = $issues
                ->join('projects_issues_tags', 'projects_issues_tags.issue_id', '=', 'projects_issues.id')
                ->join('tags', 'tags.id', '=', 'projects_issues_tags.tag_id');
        }

        $issues = $issues->where('project_id', '=', Project::current()->id);

        if ($tags)
        {
            $tags_collection = explode(',', $tags);
            $tags_amount = count($tags_collection);

            $issues = $issues->where_in('tags.tag', $tags_collection);//->get();
        }

        $issues = $issues
            ->group_by('projects_issues.id')
            ->order_by($sort_by_clause, $sort_order);

        if($tags && $tags_amount>1){
            $issues = $issues->having('count', '=', $tags_amount);
        }

        $issues = $issues->get(array('projects_issues.*'));

It returns this error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'count' in 'having clause'

like image 942
pixeline Avatar asked Aug 26 '14 22:08

pixeline


2 Answers

Use havingRaw:

$issues = $issues->havingRaw("COUNT(DISTINCT `tags`.`tag`) = ".$tags_amount);
like image 139
voodoo417 Avatar answered Sep 21 '22 22:09

voodoo417


Found the answer.

In Laravel 3:

$issues = $issues->having(DB::raw('COUNT(DISTINCT `tags`.`tag`)'),'=',$tags_amount);

I suspect @voodoo417 answer works for Laravel 4.

like image 21
pixeline Avatar answered Sep 17 '22 22:09

pixeline