#protected/migrations/m140314_091505_addProductMaterialTable.php class m140314_091505_addProductMaterialTable extends CDbMigration { public function safeUp() { $prefix = $this->getDbConnection()->tablePrefix; $this->createTable('{{productMaterial}}', array( 'id' => 'int(10) unsigned NOT NULL AUTO_INCREMENT', 'productId' => 'int(10) unsigned NOT NULL', 'materialId' => 'int(10) unsigned NOT NULL', 'PRIMARY KEY (`id`)', ), 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT=\'style (to which productMaterial should belong)\';'); $this->addForeignKey($prefix.'productMaterial_product_fk_constraint', '{{productMaterial}}', 'productId', '{{product}}', 'id', 'RESTRICT', 'CASCADE'); $this->addForeignKey($prefix.'productMaterial_material_fk_constraint', '{{productMaterial}}', 'materialId', '{{material}}', 'id', 'RESTRICT', 'CASCADE'); } }
#protected/extensions/ManyToManyRelationBehavior.php class ManyToManyRelationBehavior extends CBehavior{ /** * @var string name model Relation */ public $modelNameRelation; /** * @var string field name for the relationship with the current models */ public $fieldNameModelCurrent = null; /** * @var string field name for the relationship with the external models */ public $fieldNameModelRelation = null; /** * @var array list of values of the current model */ public $relationList = array(); public function events() { return array_merge(parent::events(), array( 'onAfterSave' => 'afterSave', )); } public function afterSave($event){ if (is_array($this->relationList)){ $model = $this->modelNameRelation; $delete = $model::model()->deleteAll("{$this->fieldNameModelCurrent} =:param", array( ":param" => $this->owner->id, )); foreach ($this->relationList as $value){ $model = new $this->modelNameRelation; $model->{$this->fieldNameModelRelation} = intval($value); $model->{$this->fieldNameModelCurrent} = $this->owner->id; if (!$model->save()){ Yii::log('Unable to save relation: '.serialize($model->getErrors()), 'warning'); return false; } } } return true; } }
public function actionCreate() { $model=new Product; $materialList = $_POST['Product']['materialId']; $model->attachBehavior('ManyToManyRelationBehavior', array( 'class' => 'ext.ManyToManyRelationBehavior', 'modelNameRelation' => 'ProductMaterial', // 'fieldNameModelCurrent' => 'productId',// Product 'fieldNameModelRelation' => 'materialId', // Material 'relationList' => $materialList, // array id material ));
#protected/models/Product.php public function relations() { return $this->moderationRelations(array( 'materialAll' => array(self::HAS_MANY, 'ProductMaterial', 'productId'), 'materialRelation' => array(self::HAS_MANY, 'Material', 'materialId', 'through' => 'materialAll'), )); }
$model = Material::model()->findByPk($pk); $model->materialAll;
Source: https://habr.com/ru/post/216605/
All Articles