I am working with an old MSSQL database that was designed years ago, as such is not set up in the best way possible. To get the relations working in my model I need to set the primary key of each model. How do I do that?
I notice the getPrimaryKey() and setPrimaryKey() methods of the class but not sure what to return or how to use them?
Now sure about MSSQL, Buy Yii will automatically populate the primarykey by the table metaData. If you want to explicitly setting the primary key you can do that by simple defining the property primaryKey:
class Tenant extends CActiveRecord
{
var $primaryKey = 'house_ref';
public static function model($className=__CLASS__)
{
return parent::model($className);
}
public function getDbConnection()
{
return Yii::app()->uhtest;
}
public function tableName()
{
return 'dbo.househ';
}
public function relations()
{
return array(
'tenancies' => array(self::HAS_MANY, 'Tenancies', 'house_ref')
);
}
}
class Tenancies extends CActiveRecord
{
public static function model($className=__CLASS__)
{
return parent::model($className);
}
public function getDbConnection()
{
return Yii::app()->uhtest;
}
public function tableName()
{
return 'dbo.tenagree';
}
public function relations()
{
return array(
'tenant' => array(self::BELONGS_TO, 'Tenant', 'house_ref')
);
}
}
Well, First thing first, You should use one of the visibility statements such as public/protected/private when defining class members, var is deprecated.
Second, You should include the entire error and callstack. Since the error you’ve displayed is very general.
As an update I have fixed this issue now. It turns out the database I was using had been designed poorly and had no primary keys assigned. I therefore needed to tell Yii what the primary keys were as Yii kept returning them as NULL forcing AR to fail. I found the answer in the guide: http://www.yiiframework.com/doc/guide/database.ar where in order to tell it the primary key I placed the primaryKey() method in the AR model. This had to be done in all other models for AR to work properly.
Everything is working great now.
I am continually pleased by how intelligent I am find Yii. Great work from all the development team.