Yii Active记录:如何在相关的many_many模型中按条件限制记录。

时间:2014-01-10 19:13:52

标签: sql activerecord yii

我有三个型号

公司(id,name)

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

专业化(id,alias,name)

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))

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

解决方案只是添加

$criteria->together=true;