2014-01-10 53 views
0

我有我的三個型號Yii活動記錄:如何通過相關many_many模型中的條件限制記錄。

公司(ID,姓名)

public function relations() 
{ 
    return array(
     'specializations' => array(self::MANY_MANY, 'Specialization', 'company_specialization(company_id, spec_id)'), 
    ); 
} 

專業化(ID,別名名稱)

public function relations() 
{ 
    return array(
     'companies' => array(self::MANY_MANY, 'Company', 'company_specialization(spec_id, company_id)'), 
    ); 
} 

CompanySpecialization(COMPANY_ID, spec_id)

我想通過專業化別名屬性找到所有擁有一組專業化的公司。

我試過了,但它無限制地返回所有記錄(yii-debug sql query here)。

$criteria=new CDbCriteria; 
    $criteria->with=array(
     'specializations' => array(
      'select'=>false, 
      'joinType'=>'INNER JOIN', 
      'condition'=>'specializations.alias IN ("spec1","spec2","spec3")', 
     ) 
    ); 
    $model=Company::model()->findAll($criteria); 

在一般我想在活動記錄的方式來獲得下一個SQL查詢:

SELECT c.name AS name 
     FROM company c 
      INNER JOIN company_specialization cs ON (c.id=cs.company_id) 
      INNER JOIN specialization s ON (s.id=cs.spec_id) 
     WHERE (s.alias IN ("spec1","spec2","spec3)) 

回答

0

幾乎沒有。你應該使用CDbCriteria::addInCondition()

$criteria=new CDbCriteria; 
$criteria->with=array(
    'specializations' => array(
     'select'=>false, 
     'joinType'=>'INNER JOIN', 
    ) 
); 
$criteria->addInCondition('specializations.alias', array("spec1","spec2","spec3"));; 
$model=Company::model()->findAll($criteria); 
0

指定標準的解決方案只需添加

$criteria->together=true;