1. Go to this page and download the library: Download arogachev/yii2-many-to-many library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
arogachev / yii2-many-to-many example snippets
/**
* @var array
*/
public $editableUsers = [];
use arogachev\ManyToMany\behaviors\ManyToManyBehavior;
/**
* @inheritdoc
*/
public function behaviors()
{
return [
[
'class' => ManyToManyBehavior::className(),
'relations' => [
[
'editableAttribute' => 'editableUsers', // Editable attribute name
'table' => 'tests_to_users', // Name of the junction table
'ownAttribute' => 'test_id', // Name of the column in junction table that represents current model
'relatedModel' => User::className(), // Related model class
'relatedAttribute' => 'user_id', // Name of the column in junction table that represents related model
],
],
],
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getUsers()
{
return $this->hasMany(User::className(), ['id' => 'user_id'])
->viaTable('tests_to_users', ['test_id' => 'id'])
->orderBy('name');
}
/**
* @return \yii\db\ActiveQuery
*/
public function getTestUsers()
{
return $this->hasMany(TestUser::className(), ['test_id' => 'id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getUsers()
{
return $this->hasMany(User::className(), ['id' => 'user_id'])
->via('testUsers')
->orderBy('name');
}
/**
* @inheritdoc
*/
public function behaviors()
{
return [
[
'class' => ManyToManyBehavior::className(),
'relations' => [
[
'name' => 'users',
// This is the same as in previous example
'editableAttribute' => 'editableUsers',
],
],
],
];
}
'autoFill' => false,
public function actionUpdate($id)
{
$model = $this->findModel($id);
$model->getManyToManyRelation('users')->fill();
// ...
}
'autoFill' => function ($model) {
return $model->scenario == Test::SCENARIO_UPDATE; // boolean value
}
'autoFill' => function ($model) {
return Yii::$app->controller->route == 'tests/default/update';
}
$model = new Test;
$model->editableUsers = [1, 2];
$model->save();
$model = new Test;
$model->editableUsers = [1, 2];
$model->save();