Foreign Key column pointing to `craft_relations` table 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' =&gt; array(static::BELONGS_TO, 'ElementRecord', 'id', 'required' =&gt; true, 'onDelete' =&gt; 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()
{
    parent::createTable();
    craft()-&gt;db-&gt;createCommand()-&gt;addForeignKey($this-&gt;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 :)