R
R
Roman Kuzmenko2018-06-14 10:19:34
MySQL
Roman Kuzmenko, 2018-06-14 10:19:34

How to correctly delete a record from the database during import?

Hello!
Introductory: Yii2, MySQL, Excel We
import data from an Excel file into the database, check if the record already exists in the database, then change it, if not, then add a new one. The question is how to delete a row from the database if it is in the database, but it is not in the import file?

$emodel = new \app\models\Products;
$exists = $emodel->find()->where(['article' => $sheetData[$baseRow]['A']])->exists();

if($exists > 0) {
 // Изменяем
} else {
// Добавляем
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dmitry Bay, 2018-06-14
@kawabanga

Not always you will go through the entire excel file at once.
About 5 years ago I worked hard on excel in php. And specifically in your task, I added the is_imported field.
Before the beginning of all import - put 0 in all lines. After the end of the import, I worked with unchanged lines.

D
Dmitry Kim, 2018-06-14
@kimono

Adding a column `is_free`.
Before starting processing, we put on the necessary lines `is_free` = 1.
We go through all the lines in the file, when adding or changing we set `is_free` = 0.
Delete all entries `is_free` = 1.

D
davidnum95, 2018-06-14
@davidnum95

We save the id of the records that have been added / changed to the array, then we remove from the database all the records that are not in the array.
Product::deleteAll(['not', ['id' => $ids]]);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question