Hello,
I have a table that will have a composite primary key with an id of "auto incremented" according to another primary key, which is a foreign key.
What is the safest way to implement this auto increment without running the risk of duplicate key made?
Can anyone help out please?
I will assume that you have two related tables, a primary table and a secondary table, thus a composite primary key, for example id and language_id
I would also expect that these two tables have data inserted to both always, first the primary table and then the secondary table.
I handle this using a behavior, in particular afterInsert() to handle the insert into the secondary table - this is an example from my language behavior:
public function afterInsert($event)
{
$owner_pk = $this->_owner->getPrimaryKey();
foreach ($this->languages as $val) {
$translation = new $this->translationClass;
$translation->{$this->languageColumn} = $val['id'];
$translation->{$this->translationForeignKey} = $owner_pk;
foreach ($this->translationColumns as $field) {
$translation->$field = $this->_owner->{$field}[$val['id']];
}
$translation->save(false);
}
}
All of my translation properties are declared in the primary class, thus $this->_owner->{$field} exists and that is where we get the values from in a form.
The behavior is declared in the primary class, eg.
public $category_name;
public $category_desc;
public $language_id;
public $translation_error;
public function behaviors() {
return [
'LanguageBehavior' => [
'class' => 'common\behaviors\LanguageBehavior',
'translationClass' => 'frontend\models\CategoryLang',
'translationForeignKey' => 'category_id',
'languageColumn' => 'language_id',
'languageRelation' => 'categoryLang',
'translationColumns' => array('category_name', 'category_desc'),
'languages' => Yii::$app->session['languages'],
],
];
}