Relational AR with Database View

Is it possible to use a db View in a relational statement?

The statement i am trying to execute is:




$a = A::model()->with('b.c.d')->findAll('id = :id', array(':id'=>$id));



Here, the relation ‘d’ would refer to an Active Record from db View. This view contains some calculations and there is a one-to-one relationship between ‘c’ and ‘d’.

The SQL statement created by Yii runs fine in MySQL. But the following error is thrown by Yii:




Invalid argument supplied for foreach()

C:\www\yii\framework\db\ar\CActiveFinder.php(838)

838: foreach($this->_pkAlias as $name=>$alias)



Hi, I am guessing by now you figured out your answer, but since this was the first result I found when looking for the solution myself, I figured I’d reply for the benefit of anyone else stuck on this. The issue is that MySQL doesn’t allow a view to have a field set as primary key, so you need to tell yii which column(s) to use as such. Simply add this to the model for your database view.




public function primaryKey()

{

    return 'enter column name to be used as primary key here';

    // For composite primary key, return an array like the following

    // return array('column name 1', 'column name 2');

}



EDIT: If you want more info here is a good starting point