Yii:按HAS_MANY关系搜索

时间:2014-08-11 06:49:42

标签: yii

我有以下表格

notice[id, type], 
property[id, type], 
property_value[id, notice_id, property_id, value].

每个通知都有自己的属性,由它的类型指定。我需要同时通过几个属性进行过滤,问题是如何指定哪个属性具有指定值?

class Notice extends CActiveRecord{

  /** @var array property_id=>value from $_GET*/
  public $searchParams= array();

  public function search() {

    $criteria = new CDbCriteria;
    // $criteria->together = true;
    $criteria->compare('t.type', $this->type);

    foreach ( $searchParams as $property_id => $value) {
      /// What should i write here?
      /// $criteria->compare('propertyValues.id', $id);
      /// $criteria->compare('propertyValues.value', $value);
    }
  }
}

Ps:找到thisthis,但我需要指定参数...

1 个答案:

答案 0 :(得分:0)

我发现这个问题围绕着经典的EAV模型(实体属性值)。因此,对于临时(但没有最好的)解决方案,我为每个参数加入值表的乘法次数:

 public function search() {    
   foreach ($properties as $id => $value) {
     $joinAlias = 'p_' . $property->id;
     $join = "\nLEFT JOIN property_value as $joinAlias ON t.id= {$joinAlias}.notice_id AND {$joinAlias}.property_id='{$property_id}'  ";
     $criteria->compare("{$joinAlias}.value", $value);
     $criteria->join .= $join;
   }
 }