When using SQL database using Yii, the framework’s implementation of active records (CActiveRecord class) is often used to create model class of the database. The active record implementation has really nice features to manipulate the data. However the following are the things to keep in mind when working with Yii’s database management framework.

Table with Multiple Primary Keys

There is actually nothing wrong with Yii’s implementation of active record for database table with composite keys (table with more than one field as primary key). However, the thing to keep in mind is that many of the automation features of Yii 1.1, the release version as of this writing, only works for table with 1 primary key field.

  1. The controller auto-generated by Gii will only generate code for 1 primary key.
  2. Gii will not generate CRUD for composite keys (See link).

Table with No Primary Key

I have been working on user access control in the past few days. The following are my tables.

[table structure goes here]

Without a primary key, the relation attribute in the auto-generated CActiveRecord model class does not work. Model classes usually contain relation attributes to another model class (based on database foreign keys). If a model class (and the corresponding table) does not have a primary key, calling the relation attribute to this class from another class will produce error.

[example code maybe]

The following is the error message I receive when using a table without a primary key:

PHP warning
Invalid argument supplied for foreach()

Partial Stack Trace:
yii/framework/db/ar/CActiveFinder.php(804): CJoinElement->populateRecord(CJoinQuery, array("t1_c0" => "1", "t1_c1" => "*", "t1_c2" => "*", "t1_c3" => "allow"))
yii/framework/db/ar/CActiveFinder.php(507): CJoinElement->runQuery(CJoinQuery)
yii/framework/db/ar/CActiveFinder.php(163): CJoinElement->lazyFind(Roles)
yii/framework/db/ar/CActiveRecord.php(281): CActiveFinder->lazyFind(Roles)