Delete multiple rows in YII2

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-08 18:51:17

问题


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.


回答1:


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




回答2:


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]);


来源:https://stackoverflow.com/questions/33899009/delete-multiple-rows-in-yii2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!