0

I have a many to many relation between products and tags.

I need to retrieve products filtered by tags, so I do it this way:

$this->Product->recursive = -1;

$options['joins'] = array(
    array('table' => 'products_tags',
        'alias' => 'ProductTag',
        'type' => 'left',
        'conditions' => array(
            'Product.id = ProductTag.product_id'
        )
    )
);

$options['conditions'] = array('ProductTag.tag_id' => $filters);

$options['fields'] = array('Product.name', 'Product.filename', 'Product.url');

$products = $this->Product->find('all', $options);

If $filters contains a single tag id, 'find' returns all products related to this tag id.

But if $filter is empty or contains several id's, find returns all products repeated the same amount of tags they have.

For example, if $filters = 1, 'find' returns all products containing tag.id = 1. Fine.

If $filters = array(1,2), 'find' returns all products containing tag.id = 1 and tag.id = 2, and if a product has tag.id = 1 and tag.id = 2 it is returned twice.

Is it possible that 'find' returns a single result even if products have multiple tags?

vonbloom
  • 1
  • 1
  • Have a look here:http://stackoverflow.com/questions/12197177/cakephp-v2-finding-duplicates-using-name-field – Franck Dec 04 '13 at 12:45
  • This is related to the resultant sql query - you can achieve the result simply by using distinct: `SELECT DISTINCT Product.* FROM ...` Don't use the join to return results. – AD7six Dec 04 '13 at 15:26

0 Answers0