mubat/yii2-inherit-model-behavior

yii2 behavior to connect inherit ActiveRecord

v1.3.2 2018-05-31 12:05 UTC

This package is not auto-updated.

Last update: 2024-12-22 07:03:09 UTC


README

Use this behavior to connect inherit ActiveRecord with (one-to-many relation)

In parent ActiveRecord should be column that uses to store ID of inherit ActiveRecord.

Extension supports 2 request formats:

  • default Yii2 input data, like:
//$_POST[]
[
    'Object' => [
        'option_1' => 'value',
        'option_2' => 'another value',
    ]
]
  • simple input names (usable for API), like:
//$_POST[]
[
    'option_1' => 'value',
    'option_2' => 'another value',
]

You can disable inherit object deletion if need.

Installation

The preferred way to install this extension is through Composer.

Either run php composer.phar require mubat/yii2-inherit-model-behavior "~1.0"

or add "mubat/yii2-inherit-model-behavior": "~1.0" to the require section of your composer.json

Usage examples

  • Options:

    • dependClass [required string] - target class name;
    • dependClassInitConfig [array] - some init configuration for target class. See \yii\app\Yii::createObject()
    • virtualOption [required string] - option name that will be use at project
    • relationMethod [string] - getter that returns with \yii\db\ActiveQuery object. By default, get[virtualOption]()
    • primaryKeyName [string] - key name at inherit model. Default "id"
    • linkAttribute [string] - column name in owner table for connect with inherit table. By default, [virtualOption]_id
    • createDependObjectOnEmpty [boolean] - you can disable empty inherit object creation if need. By default, true
    • simpleRequest [boolean] - How need to parse simple options: like 'bar' (true) or like 'Foo[bar]' (false) at request. By default, false
    • deleteWithOwner - with this option you can disable/enable run delete() action on inherit object. Default: true (It also can change status during processing on the fly)
  • Usage:

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['image'] = [
            'class' => InheritModelBehavior::class,
            'dependClass' => Image::class, //required
            'virtualOption' => 'image', //required
            'linkAttribute' => 'image_id',
            'relationMethod' => 'getSavedImage',
            'simpleRequest' => true,
            'deleteWithOwner' => true,
        ];
        return $behaviors;
    }
    
    /** @return \yii\db\ActiveQuery */
    public function getSavedImage()
    {
        return $this->hasOne(Image::class, ['id' => 'image_id']);
    }