Help with active record

Hi all !

I am fairly new to yii and I nedd some help with active record.

Let say you have a class (let say class1 )with a relation

‘class20’ => array(self::BELONGS_TO, ‘class2’, ‘class2’),

and that class (class2) has a relation

‘class30’ => array(self::BELONGS_TO, ‘class3’, ‘class3’),

I want to get all elements of the initial(class1) where class3 meets a certain criteria.

Easy to do with plain sql, but how do I do that with active record ?

Also is there a more extended documentation or example tutorial for active record

Thanks !

It would be easier to understand this question with real table/model names instead of random numbers.

Active record is not a replacement for using SQL, it is a way of working more efficiently with it. There is probably a way to do this with Active Record, but I would simply do this.

$models = Class1::model()->findAllBySql("SELECT class1.* FROM class1 INNER JOIN class2 INNER JOIN class3 WHERE ...");


$criteria = new CDbCriteria;

$criteria->condition = "your conditions for class3 as in a SQL statement but without 'WHERE'";

$join = Array('class2', 'class2.class1');

$class3s = Class3::model()->with($join)->findAll($criteria);

//now you want the class1s

$class1s = Array();

foreach ($class3s as $class3)

	foreach ($class3s->class2 as $class2)

	  	foreach ($class2->class1 as $class1)

			$class1s[] = $class1;

Looks pretty ugly now that I look at it :blink: perhaps this would do better (similar to alexs solution):

$connection = Yii::app()->db;

$sql = "your sql with joins and everything";

$cmd = $connection->createCommand($sql);

$reader = $cmd->queryAll();

$class1s = Array();

foreach ($reader as $row){

	$class1 = new Class1;

	$class1->attr1 = $row->whatever




	$class1s[] = $class1;


Been a way for a few days I mada solution using ordinary sql at the end.

Thanks for the suggestions