Re-defining primary key

Hi all,

I have a table with the following schema in MySQL:

CREATE TABLE snmp_trap (


   recv_date DATE NOT NULL, -- just for partitioning only

   recv_time DATETIME NOT NULL,

   trap_oid CHAR(100) NOT NULL,

   -- recv_date is included as partition key has to be 

   -- included in any 'unique' key, including primary key

   PRIMARY KEY(snmp_trap_id, recv_date) 




and created a model ‘SnmpTrap’ using gii.

The problem is that the primary key I really want is just ‘snmp_trap_id’ not

(snmp_trap_id, recv_date) guessed by Yii. By following the advice in overriding primary key, which suggest adding the following to ‘SnmpTrap’ model:

public function init()


   $this->getMetaData()->tableSchema->primaryKey = 'snmp_trap_id';


I can have an array of active record with correct primary key. But when calling

SnmpTrap::model()->findByPk(some_pk), it return errors. It seems that the init()

function is skipped when calling the class method SnmpTrap::model(). What should I


Thanks in advance.

As you’ve overridden the function init, you can do the same with ::model:

public static function model($className=__CLASS__)


        // Added by me:

        $this->getMetaData()->tableSchema->primaryKey = 'snmp_trap_id';

        return parent::model($className);


I haven’t tested this.

Another option is to create a function ClassName, which will be run whenever an instance is created, and set the primaryKey there.

Let me know if it works!

Thank you for your quick reply.

I’ve tried it and it seems there is no ‘$this’ in static function like ‘model()’. And it doesn’t work

either when I replaced ‘$this->’ with ‘self::’, it may because getMetaData() is a member function.

How about just defining it in the model as a function.


public function primaryKey()


    return 'yourColumn';


EDIT: Sorry - I just read the link and realized this was already attempted.