2017 © Pedro Peláez
 

yii2-extension yii2-relational-behavior

Easy saving relational models in yii2

image

e96/yii2-relational-behavior

Easy saving relational models in yii2

  • Wednesday, December 20, 2017
  • by m8rge
  • Repository
  • 6 Watchers
  • 4 Stars
  • 8,792 Installations
  • PHP
  • 0 Dependents
  • 0 Suggesters
  • 4 Forks
  • 0 Open issues
  • 2 Versions
  • 5 % Grown

The README.md

Yii2 Relational behavior

This behavior allows you to set relations in your code. Also, it saves many-to-many relations declared with via() or viaTable(), (*1)

Relations accepts int|int[]|ActiveRecord|ActiveRecord[]., (*2)

Install

php composer.phar require e96/yii2-relational-behavior:dev-master

Setup

In model:, (*3)

class User extends ActiveRecord
{
    public function behaviors()
    {
        return [
            e96\behavior\RelationalBehavior::className(), // enable behavior
        ];
    }

    public function rules()
    {
        return [
            ['permissions', 'safe'], // allow set permissions with setAttributes()
        ];
    }

    // define many-to-many relation
    public function getPermissions()
    {
        return $this->hasMany(Permission::className(), ['id' => 'permissionId'])
            ->viaTable('user-map-permission', ['userId' => 'id']);
    }
}

In view:, (*4)

$form->field($model, 'permissions')->dropDownList($permissions, ['multiple' => true])

Usage

$user->load(Yii::$app->request->post());
$user->save();

Other usages:, (*5)

$user = User::findOne(1);
$user->permissions = 1;
// or
$user->permissions = [1,2];
// or
$user->permissions = Permission::findOne(1);
// or
$user->permissions = Permission::find()->all();
// or
$user->load(Yii::$app->request->post());
// or
$user->setAttributes(['permissions' => [1,2]]);
// then
$user->save();

Written with StackEdit., (*6)

The Versions

20/12 2017

dev-master

9999999-dev

Easy saving relational models in yii2

  Sources   Download

MIT

The Requires

 

yii2 behavior related relational pk primary

29/01 2016

dev-default-scope-fix

dev-default-scope-fix

Easy saving relational models in yii2

  Sources   Download

MIT

The Requires

 

yii2 behavior related relational pk primary