Delete multiple lines in YII2

I have an array of objects extracted from a database:

$masterListContacts = MasterListContacts::find() ->select('master_list_contacts.*') ->innerJoin('master_contacts', '`master_contacts`.`id` = `master_list_contacts`.`master_contact_id`') ->with('masterContact') ->where(['user_id' => \Yii::$app->user->identity->id, 'slug' => $slug]) ->all(); 

Under certain circumstances, I need to delete all rows from the database represented in this array. But with the delete () and deleteAll () methods, I got a Call to a member function ... on array error. Can someone please tell me which one is the best way to achieve this.

UPDATE: Here is my database structure.

+5
source share
2 answers

Found the best solution:

 \Yii::$app ->db ->createCommand() ->delete('master_contacts', ['id' => $deletableMasterContacts]) ->execute(); 

Where $deletableMasterContacts is an array of master_contacts identifiers to be removed

+8
source

You can safely delete ->select('master_list_contacts.*') .

 ->innerJoin('master_contacts', '`master_contacts`.`id` = `master_list_contacts`.`master_contact_id`') 

does the same job as ->joinWith('masterContact') .

To remove, use this code:

 MasterListContacts::deleteAll(['user_id' => \Yii::$app->user->identity->id, 'slug' => $slug]); 
+6
source

Source: https://habr.com/ru/post/1236722/


All Articles