Skip to content

Instantly share code, notes, and snippets.

@svilenkov
Forked from samdark/taggable_or.php
Created October 3, 2012 13:48
Show Gist options
  • Select an option

  • Save svilenkov/3826994 to your computer and use it in GitHub Desktop.

Select an option

Save svilenkov/3826994 to your computer and use it in GitHub Desktop.

Revisions

  1. svilenkov revised this gist Oct 3, 2012. 1 changed file with 1 addition and 0 deletions.
    1 change: 1 addition & 0 deletions taggable_or.php
    Original file line number Diff line number Diff line change
    @@ -18,6 +18,7 @@ protected function getFindByAnyTagsCriteria($tags) {
    $tags = implode(', ', $tags);

    $criteria->select = 't.*';
    $criteria -> distinct = true;
    $criteria->join .=
    "JOIN {$this->getTagBindingTableName()} bt ON t.{$pk} = bt.{$this->getModelTableFkName()}
    JOIN {$this->tagTable} tag ON tag.{$this->tagTablePk} = bt.{$this->tagBindingTableTagId} AND tag.`{$this->tagTableName}` IN ($tags)";
  2. @samdark samdark created this gist Oct 3, 2012.
    48 changes: 48 additions & 0 deletions taggable_or.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,48 @@
    /**
    * Get criteria to limit query to match any of tags specified
    * @access private
    * @param array $tags
    * @return CDbCriteria
    */
    protected function getFindByAnyTagsCriteria($tags) {
    $criteria = new CDbCriteria();

    $pk = $this->getOwner()->tableSchema->primaryKey;

    if(!empty($tags)){
    $conn = $this->getConnection();
    foreach($tags as &$tag) {
    $tag = $conn->quoteValue($tag);
    }
    unset($tag);
    $tags = implode(', ', $tags);

    $criteria->select = 't.*';
    $criteria->join .=
    "JOIN {$this->getTagBindingTableName()} bt ON t.{$pk} = bt.{$this->getModelTableFkName()}
    JOIN {$this->tagTable} tag ON tag.{$this->tagTablePk} = bt.{$this->tagBindingTableTagId} AND tag.`{$this->tagTableName}` IN ($tags)";
    }
    }

    if($this->getScopeCriteria()){
    $criteria->mergeWith($this->getScopeCriteria());
    }

    return $criteria;
    }

    /**
    * Limit current AR query to have any of tags specified.
    * @param string|array $tags
    * @return CActiveRecord
    */
    public function taggedWithAnyOf($tags) {
    $tags = $this->toTagsArray($tags);

    if(!empty($tags)){
    $criteria = $this->getFindByAnyTagsCriteria($tags);
    $this->getOwner()->getDbCriteria()->mergeWith($criteria);
    }

    return $this->getOwner();
    }