CSqlDataProvider with Composite Key Fields

Hi,

I’m trying to create a CSqlDataProvider from a table database with composite primary keys. Which value value must assign to keyField ?

Thanks in advance!

Pedro

Hi Pedro, welcome to the forum.

We can specify composite PK for CActiveRecord::primaryKey by an array like “array(‘pk1’, ‘pk2’)”.

But CSqlDataProvider doesn’t support composite PK for “keyField”. It must be a string, not an array.

And the values of keyField must be unique among each other.

I think you can get a virtual single PK field concatenating the PKs and use it as "keyField".




$count=Yii::app()->db->createCommand('SELECT COUNT(*) FROM mytable')->queryScalar();

$sql='SELECT *, concat(pk1, "-", pk2) as keyfield FROM mytable';

$dataProvider=new CSqlDataProvider($sql, array(

    'totalItemCount'=>$count,

    'keyField'=>'keyfield',

    ...

));



Sorry if it doesn’t work. I haven’t tested it.