Within a plugin I'd like to create a table which is linked to the craft_users
table, keyed on the id
. In my table I have a user_id
column which I'd like to be unique and only contain Id's which exist in the craft_users
table. Now, I know I can't monkey about with the craft_users
table or the UserRecord
, so I wondered what the best way of doing this would be?
Here is my Record code:
<?php
namespace Craft;
class MyPlugin_MerchantRecord extends BaseRecord
{
public function getTableName()
{
return 'myplugin_merchants';
}
protected function defineAttributes()
{
return [
'user_id' => [AttributeType::Number, 'required' => true],
...
];
}
public function defineIndexes()
{
return [
['columns' => ['user_id'], 'unique' => true],
];
}
public function defineRelations()
{
return [
'user' => [static::BELONGS_TO, 'UserRecord', 'user_id'],
];
}
}
If I try and install the plugin I get the following error:
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint.
The SQL statement executed was: ALTER TABLE `craft_myplugin_merchants`
ADD CONSTRAINT `craft_myplugin_merchant_user_id_fk` FOREIGN KEY (`user_id`)
REFERENCES `craft_users` (`id`) ON DELETE SET NULL
I've tried it with/without the defineIndexes()
call, and get the same error. I'm sure I'm missing something simple, but can't see the wood for the trees!
As always any help gratefully received.