Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete multiple rows in YII2

Tags:

yii2

I have an array of objects fetched from 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 both delete() and deleteAll() methods I got an error Call to a member function ... on array. Could someone tell me please which one is the best way to accomplish this?

UPDATE: Here is my database structure.

like image 413
Avag Sargsyan Avatar asked Nov 24 '15 16:11

Avag Sargsyan


2 Answers

Found better solution:

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

Where $deletableMasterContacts is array of master_contacts ids, which should be deleted

like image 62
Avag Sargsyan Avatar answered Nov 17 '22 09:11

Avag Sargsyan


You can painlessly remove ->select('master_list_contacts.*').

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

performs the same work that ->joinWith('masterContact').

For delete entites try use this code:

MasterListContacts::deleteAll(['user_id' => \Yii::$app->user->identity->id, 'slug' => $slug]);
like image 29
Onedev_Link Avatar answered Nov 17 '22 10:11

Onedev_Link