CActiveRecord question

Hello everyone.

Can anybody help me please?

I need to select records matching some condition from one table, but only those records should be selected which ids exist in another table. How can I do it using CactiveRecord?

Thanks.

Your question implies there’s a relation between table1 and table2. You should specify that relation in your model, something like


	

public function relations()

{

    return array(

        'relToTable2'=>array(SELF::HAS_MANY,'Table2','foreignkeyfromTable1inTable2'),

    );

}



This relation has standard inner join.

Use the relation in your controller:




$model=Table1::model()->with('relToTable2')->findAll($myconditions);



I tried this but it returns record from table1 as many times as it is found in table2. And also it returns records from table1 whose ids do not exist in table2. My purpose is to select only those records from table1 whose ids exist in table2.

You can specify the jointype if you get all the records http://www.yiiframework.com/doc/api/1.1/CActiveRelation#joinType-detail (my bad, it defaults to left outer join in stead of inner join).

Either way, you have to specify the grouping to get the ‘first’ record of table 2.


public function relations()

{

    return array(

        'relToTable2'=>array(SELF::HAS_MANY,'Table2','foreignkeyfromTable1inTable2',array('group'=>'foreignkey','joinType'=>'inner join')),

    );

}