4

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?

Lindsey D
  • 23,974
  • 5
  • 53
  • 110

1 Answers1

5

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()
{
    parent::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 :)

Mats Mikkel Rummelhoff
  • 22,361
  • 3
  • 38
  • 69