Vipul
Vipul

Reputation: 655

How to deleteAll() records which has a foreign key relationship with other table

I need to delete all the records from agency_permissions where it's module_type inside permissions table is 1. How to achieve it in Yii2, somewhat similar to deleteAll()->joinWith() instead of using direct sql delete command. Looking for a Yii2 way of achieving this task. Below are the tables:

permissions

+-----+-----------------------------------------------+-------------+
| 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 |
+----+---------+---------------+

Upvotes: 0

Views: 1389

Answers (1)

marche
marche

Reputation: 1756

If you have both Permissions.php and AgencyPermissions.php models or similar, you can do something like this:

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

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

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

Upvotes: 2

Related Questions