Delete multiple rows in YII2

2019-06-20 01:41发布

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 the best way to accomplish this?

UPDATE: Here is my database structure.

标签: yii2
2条回答
欢心
2楼-- · 2019-06-20 01:59

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]);
查看更多
Lonely孤独者°
3楼-- · 2019-06-20 02:04

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

查看更多
登录 后发表回答