PHP code example of mdmsoft / yii2-ar-behaviors

1. Go to this page and download the library: Download mdmsoft/yii2-ar-behaviors 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/ */

    

mdmsoft / yii2-ar-behaviors example snippets


class Sales extends ActiveRecord
{
    ...
    public static function defaultScope($query)
    {
        $query->andWhere(['status' => self::STATUS_OPEN]);
    }

    public static function bigOrder($query, $ammount=100)
    {
        $query->andWhere(['>','ammount',$ammount]);
    }
}

----
// get all opened sales
Sales::find()->all(); // apply defaultScope

// opened sales and order bigger than 200
Sales::find()->bigOrder(200)->all();


/**
 * @property integer $id
 * @property string $full_name
 * @property string $organisation
 * @property string $address1
 * @property string $address2
 */
class CustomerDetail extends ActiveRecord
{
    
}

/**
 * @property integer $id
 * @property string $name
 * @property string $email
 */
class Customer extends ActiveRecord
{
    
    public function behaviors()
    {
        return [
            [
                'class' => 'mdm\behaviors\ar\ExtendedBehavior',
                'relationClass' => CustomerDetail::className(),
                'relationKey' => ['id' => 'id'],
            ],
        ];
    }
}

$model = new Customer();

$model-name = 'Doflamingo';
$model->organisation = 'Donquixote Family';
$model->address = 'North Blue';

$model->save(); // it will save this model and related model

class Order extends ActiveRecord
{
    public function getItems()
    {
        return $this->hasMany(Item::className(),['order_id'=>'id']);
    }

    public function behaviors()
    {
        return [
            [
                'class' => 'mdm\behaviors\ar\RelationBehavior',
                'beforeRSave' => function($item){
                    return $item->qty != 0;
                }
            ],
        ];
    }
}

$model = new Order();

if($model->load(Yii::$app->request->post()){
    $model->items = Yii::$app->request->post('Item',[]);
    $model->save();
}

class Order extends ActiveRecord
{
    use \mdm\behavior\ar\RelationTrait;

    public function getItems()
    {
        return $this->hasMany(Item::className(),['order_id'=>'id']);
    }

    public function setItems($value)
    {
        $this->loadRelated('items', $value);
    }

    public function beforeRSave($item)
    {
        return $item->qty != 0;
    }
    
}

$model = new Order();

if($model->load(Yii::$app->request->post()){
    $model->items = Yii::$app->request->post('Item',[]);
    $model->save();
}