Question

I have the following code which gets products based on tags:

self::factory('user_product')
    ->join('items', 'INNER')->on('user_product.item_id', '=', 'items.id')
    ->join('user_tags', 'INNER')->on('items.id', '=', 'user_tags.item_id')
    ->join('tags', 'INNER')->on('user_tags.tag_id', '=', 'tags.id')
    ->where('tags.title', 'IN', $tags)
    ->order_by('items.created_at', 'DESC')->group_by('items.id')->find_all();

Which generates the following SQL:

SELECT `user_product`.* FROM `user_products` AS `user_product`
INNER JOIN `items` ON (`user_product`.`item_id` = `items`.`id`) 
INNER JOIN `user_tags` ON (`items`.`id` = `user_tags`.`item_id`)
INNER JOIN `tags` ON (`user_tags`.`tag_id` = `tags`.`id`)
WHERE `tags`.`title` IN ('tag1', 'tag2')
GROUP BY `items`.`id`
ORDER BY `items`.`created_at` DESC

I would like to modify my query so that it returns only those user_products that have both tag1 and tag2 (in the where in statement). So I think I need to add the following after the WHERE:

HAVING COUNT(DISTINCT `tags`.`title`) = 2

How would I do this using Kohana's ORM, at the moment I have the following but can't work out how to integrate the COUNT and DISTINCT methods:

->having_open()->having('tags.title','=','2')->having_close();
Was it helpful?

Solution

Got it work using the following:

->having_open()->having(DB::expr('COUNT(DISTINCTtags.title)'),'=',2)->having_close();

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top