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'
Use havingRaw
:
$issues = $issues->havingRaw("COUNT(DISTINCT `tags`.`tag`) = ".$tags_amount);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With