I am trying to implement multi-select drop down using "cornernote/yii2-linkall " and “kartik-v/yii2-widget-select2”. it works good for single multi-select drop down, so now I’m trying to implement two multi-select drop down in single form but here I’m stuck. when I repeatedly perform update function it gives Integrity constraint violated error.
Database tables looks as below:
part(id, name)
industry(id,name)
supplier_to_part(supplier_id, part_id)
supplier_to_industry(supplier_id, industry_id)
main table is :- supplier (id,…)
Is there anything wrong with the afterSave()?? Any help
Supplier.php model
<?php
namespace frontend\models;
use Yii;
use yii\web\UploadedFile;
use yii\db\ActiveRecord;
use yii\behaviors\TimestampBehavior;
use common\models\MasterAdmin;
use cornernote\linkall\LinkAllBehavior;
use frontend\models\Industry;
class Supplier extends MasterAdmin
{
/**
* @inheritdoc
*/
public $part_ids;
public $industry_ids;
public function behaviors()
{
return [
\cornernote\linkall\LinkAllBehavior::className(),
];
}
public static function tableName()
{
return 'supplier';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
.....
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
......
];
}
public function afterSave($insert, $changedAttributes)
{
$parts = [];
$industries = [];
// foreach (array_merge($this->part_ids,$this->industry_ids) as $part_name ) {
foreach ($this->part_ids as $part_name ){
foreach ($this->industry_ids as $industry_name ){
$part = Part::getPartByName($part_name);
$industry = Industry::getIndustryByName($industry_name);
if ($part ||$industry ) {
$parts[] = $part;
$industries[] = $industry;
}
}
}
$this->linkAll('industries', $industries );
$this->linkAll('parts', $parts );
parent::afterSave($insert, $changedAttributes);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getSupManpowers()
{
return $this->hasMany(SupManpower::className(), ['supplier_id' => 'id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getUser()
{
return $this->hasOne(User::className(), ['id' => 'user_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getSupplierToParts()
{
return $this->hasMany(SupplierToPart::className(), ['supplier_id' => 'id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getParts()
{
return $this->hasMany(Part::className(), ['id' => 'part_id'])->viaTable('supplier_to_part', ['supplier_id' => 'id']);
}
/**
* @return \yii\db\ActiveQuery
*/
/**
* @return \yii\db\ActiveQuery
*/
public function getSupplierToIndustries()
{
return $this->hasMany(SupplierToIndustry::className(), ['supplier_id' => 'id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getIndustries()
{
return $this->hasMany(Industry::className(), ['id' => 'industry_id'])->viaTable('supplier_to_industry', ['supplier_id' => 'id']);
}
}