matthew-p/yii2-delete-relations

Yii2 删除关系行为

dev-master 2018-10-19 08:14 UTC

This package is auto-updated.

Last update: 2023-08-19 23:43:24 UTC


README

Yii2 删除关系行为

安装

安装此扩展的首选方式是通过 composer

运行以下命令之一

php composer.phar require --prefer-dist matthew-p/yii2-delete-relations "@dev"

或者

"matthew-p/yii2-delete-relations": "@dev"

将以下内容添加到您的 composer.json 文件的 require 部分。

用法

安装扩展后,只需在您的代码中使用它即可

将行为添加到 Active Record 类

use MP\Yii2DeleteRelations\DeleteRelationsBehavior;
use yii\db\ActiveRecord;

class Sample extends ActiveRecord
{
    /**
     * @inheritdoc
     */
    public function behaviors(): array
    {
        return [
            [
                'class'     => DeleteRelationsBehavior::class,
                'relations' => ['categories', 'phone', 'orders'],  // Delete all relations bulk
                'method'    => ['orders' => 0, 'phone' => DeleteRelationsBehavior::DELETE_BY_ONE], // orders - update relation column to 0, phone - use delete method
            ],
        ];
    }
    
    /**
     * Get categories
     *
     * @return ActiveQuery|CategoriesQuery
     */
    public function getCategories(): CategoriesQuery
    {
        return $this->hasMany(Category::class, ['id' => 'category_id']);
    }
    
    /**
     * Get orders
     *
     * @return ActiveQuery|OrdersQuery
     */
    public function getOrders(): OrdersQuery
    {
        return $this->hasMany(Order::class, ['id' => 'order_id']);
    }
    
    /**
     * Get phone
     *
     * @return ActiveQuery|PhoneQuery
     */
    public function getPhone(): PhoneQuery
    {
        return $this->hasOne(Phone::class, ['id' => 'phone_id']);
    }
}

这就完成了。检查一下吧。