PHP code example of jonatas-sas / yii2-m2m-behavior

1. Go to this page and download the library: Download jonatas-sas/yii2-m2m-behavior 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/ */

    

jonatas-sas / yii2-m2m-behavior example snippets


use yii\db\ActiveRecord;
use yii\db\ActiveQuery;
use odara\yii\behaviors\LinkManyToManyBehavior;

/**
 * @property int        $id
 * @property string     $name
 *
 * @property-read Tag[] $tags
 * @property int[]      $tagIds
 */
class Item extends ActiveRecord
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'tags' => [
                'class' => LinkManyToManyBehavior::class,
                'relation' => 'tags',
                'referenceAttribute' => 'tagIds',
                'deleteOnUnlink' => true,
                'extraColumns' => [
                    'source' => 'admin',
                    'created_at' => static fn (): int => time(),
                ],
            ],
        ];
    }

    /**
     * Returns the relation between Item and Tag models.
     *
     * @return ActiveQuery
     */
    public function getTags(): ActiveQuery
    {
        return $this->hasMany(Tag::class, ['id' => 'tag_id'])
            ->viaTable('item_tag', ['item_id' => 'id']);
    }
}

echo $form->field($model, 'tagIds')->checkboxList(
    Tag::find()
        ->select(['name', 'id'])
        ->indexBy('id')
        ->column()
);