如何deleteAll()记录与其他表有外键关系

时间:2016-11-25 12:06:49

标签: yii2 yii2-advanced-app

我需要删除agency_permissionspermissions表中的module_type为1的所有记录。如何在Yii2中实现它,有点类似于deleteAll()->joinWith()而不是使用直接sql delete命令。寻找实现此任务的Yii2方式。以下是表格:

权限

+-----+-----------------------------------------------+-------------+
| id  | title                                         | module_type |
+-----+-----------------------------------------------+-------------+
| 134 | Case / Container                              |           1 |
| 141 | Container > Status                            |           1 |
| 146 | Container > Topic/Sub-topic                   |           1 |
| 150 | Container > Facility/ Sub-facility            |           1 |
| 275 | Allow other cities to compare with this city? |           0 |
| 276 | Activate Outlook Module (choose yes)          |           0 |
+-----+-----------------------------------------------+-------------+

agency_permissions

+----+---------+---------------+
| id | govt_id | permission_id |
+----+---------+---------------+
|  1 |      22 |           134 |
|  2 |      22 |           141 |
|  3 |      22 |           146 |
|  4 |      22 |           150 |
|  5 |      22 |           275 |
|  6 |      22 |           276 |
+----+---------+---------------+

1 个答案:

答案 0 :(得分:1)

如果您同时拥有Permissions.phpAgencyPermissions.php模型或类似模型,则可以执行以下操作:

$permissions = Permissions::find()
    ->select('id')
    ->asArray()
    ->where(['module_type' => 1])
    ->all();

$permissionsIds = ArrayHelper::getColumn($permissions, 'id');

$rowsDeleted = AgencyPermissions::deleteAll(['permission_id' => $permissionsIds]);