PHP code example of ed-smartass / yii2-relation-behavior

1. Go to this page and download the library: Download ed-smartass/yii2-relation-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/ */

    

ed-smartass / yii2-relation-behavior example snippets


use Smartass\Yii2RelationBehavior\RelationBehavior;

// ...

/**
 * @inheritdoc
 */
public function behaviors()
{
    return [
        // ...
        'relation' => [
            'class' => RelationBehavior::class,
            'relations' => [
                // Many to one relation
                'manufacturer' => [
                    'target' => Manufacturer::class,
                    'link' => ['manufacturer_id' => 'manufacturer_id']
                ],
                // One to many relation
                'modelCategories' => [
                    'target' => ModelCategories::class,
                    'link' => ['model_id' => 'model_id'],
                    'multiple' => true
                ],
                // Many to many relation
                'categories' => [
                    'target' => Category::class,
                    'link' => ['category_id' => 'category_id'],
                    'multiple' => true,
                    'via' => 'modelCategories'
                ]
            ]
        ]
        // ...
    ];
}

// ...

public function getCategories()
{
    return $this->hasMany(...);
}

$model->categories = [
    ['category_id' => 1], // Will find (or create if not exists) category with category_id `1`
    ['category_id' => 2, 'name' => 'New name'], // Will find (or create) category with category_id `1` and change name
    ['name' => 'New category'] // Will create new category
];
$model->save();

/**
 * @inheritdoc
 */
public function rules()
{
    return [
        // ...
        ['categories', 'safe'],
        // ...
    ];
}