?>

RelationalBehavior - behavior that simplifies work with many-to-many relations

Imagine we have:

  • product table
  • table with product properties
  • and table of relations of products and properties

In the language of Yii2, this will look like:

<?php class Product extends \yii\db\ActiveRecordInterface { public function behaviors() { return [ \skeeks\cms\behaviors\RelationalBehavior::className(), // enable behavior ]; } public function rules() { return [ ['properies', 'safe'], // allow set permissions with setAttributes() ]; } // define many-to-many relation public function getProperies() { return $this->hasMany(Property::className(), ['id' => 'property_id']) ->viaTable('product2properties', ['product_id' => 'id']); } } 

With one exception, we declared behavior

\ skeeks \ cms \ behaviors \ RelationalBehavior 

It will uplift our life in the future.

Now, to build a form for editing this product, you can just write:

<?= $form->field($model, 'properties')->checkboxList(\yii\helpers\ArrayHelper::map( Property::find()->all(), 'id', 'name' )); ?> 

More examples for clarity, what opportunities gives this behavior:

$product = Product::findOne(1); $product->properties = 1; // or $product->properties = [1,2]; // or $product->properties = Property::findOne(1); // or $product->properties = Property::find()->all(); // or $product->load(Yii::$app->request->post()); // or $product->setAttributes(['properties' => [1,2]]); // then $product->save(); 

All Comments (0)
No Comments