Search code examples
phpmysqlsymfony-1.4propel

Join statement for multiple values


This is something that really bugs me, but first the code, then the question:

<?php
 public static function retrievePagerByTagArray($page, $limit, $tags) {

    $criteria = new Criteria();

    $criteria->addJoin(self::MASTER_ID, MasterPeer::MASTER_ID);

    foreach($tags as $tag) {
      $criteria->addOr(MasterHasTagPeer::TAG_ID, $tag->getPrimaryKey());
    }

    $criteria->add(self::IS_ACTIVE, 1);
    $criteria->addDescendingOrderByColumn(self::MASTER_ID);
    $pager = new sfPropelPager('Master');

    $pager->setCriteria($criteria);
    $pager->setPage($page);
    $pager->setMaxPerPage($limit);
    $pager->init();
    return $pager;
  }

What i want to do is this:

my tags are made with get parameters so tags come like http://example.com?filter=tag1%7tag2 etc... i convert those tags to their corresponding tagid and want to filter my results to just the stuff that has those too parameters meaning:

master_has_tag is an n:m-table only storing the ids.

I know that the $criteria->addOr(MasterHasTagPeer::TAG_ID, $tag->getPrimaryKey()); is not what im looking for since this is giving me all entries containing atleast one of the filters


Solution

  • It sounds like you want to build a query with WHERE tag_id IN (1, 2, 3, 4...). However, I'm not familiar with Symony or Propel so you will need to find the corresponding method.

    If $tags is an array of ids you can use implode() to combine the ids into a comma-separated string.

    $tag_ids = implode(',', $tags);
    

    If $tags is an array of objects then you can use array_map() to make the same thing.

    // create an array of tag ids
    $tags = array_map(function($tag) {
      return $tag->getPrimaryKey();
    }, $tags);
    
    // create a comma-separated string of ids
    $tag_ids = implode(',', $tags);