11

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.

2 Answers 2

13

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

Sign up to request clarification or add additional context in comments.

1 Comment

Probably better to use the function specified for this. deleteAll()
11

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

2 Comments

Thank you for your answer @Onedev.Link, but it throws an error: Unknown column 'user_id' in 'where clause' since I need to join table 'master_contacts' to do this......and just wondering does yii provide a way to do foreach($masterListContacts as $record) $record->delete(); but querying database once.
Yeah. You can use foreach($masterListContacts as $record) $record->delete(); code. Unknown column 'user_id' in 'where clause' say that table MasterListContacts::tableName() does't have user_id field. What is your database structure? If you want delete records only with relation record in master_contacts you should use leftJoin.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.