<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
nyx-solutions / yii2-nyx-ar-many-to-many-link example snippets
class Item extends ActiveRecord
{
public function behaviors()
{
return [
'linkGroupBehavior' => [
'class' => LinkManyToManyBehavior::className(),
'relation' => 'groups', // relation, which will be handled
'relationReferenceAttribute' => 'groupIds', // virtual attribute, which is used for related records specification
],
];
}
public static function tableName()
{
return 'Item';
}
public function getGroups()
{
return $this->hasMany(Group::className(), ['id' => 'groupId'])->viaTable('ItemGroup', ['itemId' => 'id']);
}
}
// Pick up related model primary keys:
$groupIds = Group::find()
->select('id')
->where(['isActive' => true])
->column();
$item = new Item();
$item->groupIds = $groupIds; // setup related models references
$item->save(); // after main model is saved referred related models are linked
$groups = Group::find()
->where(['isActive' => true])
->all();
$item = new Item();
$item->save();
foreach ($groups as $group) {
$item->link('groups', $group);
}
$item = Item::findOne(15);
$item->groupIds = array_merge($item->groupIds, [17, 21]);
$item->save(); // groups "17" and "21" will be added
$item->groupIds = [5];
$item->save(); // all groups except "5" will be removed
class Item extends ActiveRecord
{
public function rules()
{
return [
['groupIds', 'safe'] // ensure 'groupIds' value can be collected on `populate()`
// ...
];
}
// ...
}
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $model Item */
use yii\web\Controller;
class ItemController extends Controller
{
public function actionCreate()
{
$model = new Item();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view']);
}
return $this->render('create', ['model' => $model]);
}
// ...
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.