【问题标题】:How to deleteAll() records which has a foreign key relationship with other table如何删除与其他表有外键关系的All()记录
【发布时间】:2016-11-26 03:04:35
【问题描述】:

我需要从agency_permissions 中删除所有记录,其中permissions 表中的module_type 是1。 Yii2中如何实现,有点类似deleteAll()->joinWith(),而不是直接使用sql删除命令。寻找完成此任务的 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 |
+----+---------+---------------+

【问题讨论】:

    标签: yii2 yii2-advanced-app


    【解决方案1】:

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

    $permissions = Permissions::find()
        ->select('id')
        ->asArray()
        ->where(['module_type' => 1])
        ->all();
    
    $permissionsIds = ArrayHelper::getColumn($permissions, 'id');
    
    $rowsDeleted = AgencyPermissions::deleteAll(['permission_id' => $permissionsIds]);
    

    【讨论】:

    • 所以没有这样的东西:->deleteAll()->joinWith('permissions')->where(['permission_id' = $permissionsIds]);对吧?
    • 我在 ActiveRecord 的文档中没有看到。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-26
    • 2019-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多