I am writing a plugin with a Record. I want the primary key of the table to also be a foreign key relating to the craft_relations table. Ordinarily, I would add something like this...

public function defineRelations()
    return array(
        'element' => array(static::BELONGS_TO, 'ElementRecord', 'id', 'required' => true, 'onDelete' => static::CASCADE),

However, it seems like the craft_relations table does not have a matching Record.

How can I add a primary key column which is also a foreign key?


I might be wrong, but I don't believe you'll be able to do that within the defineRelations() method – Craft needs a record class for the table you want to create a relation with.

A workaround is to override the createTable() method in your record class and add the foreign key constraint manually using DbCommand:

public function createTable()
    craft()->db->createCommand()->addForeignKey($this->getTableName(), 'id', 'relations', 'id', 'CASCADE', 'CASCADE');

To be perfectly honest the above feels quite hacky and there might be a better way – but it seems to work :)

  • 2
    Yeah that's probably the best way for now 😞 – Brandon Kelly Aug 11 '16 at 14:22
  • Thanks Mats, that sounds like a solid workaround! (And thanks Brandon for confirming.) – Lindsey D Aug 11 '16 at 20:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.