S
S
smigles2020-02-04 02:59:00
Yii
smigles, 2020-02-04 02:59:00

How to synchronize records in a database with an array?

There is an array obtained based on data from a form, a view, and a set of records in a table in the view's database:['value1', 'value2', 'value3', ...]

group | value
--------------
1     | value1
1     | value2
1     | value3
1     | ...

You need to synchronize the records in the database with the array as follows:
  1. If the value is not in the table, but it is in the array, then you need to add this value to the table.
  2. If the value is not in the array, but it is in the table, then you need to delete this value from the table.
  3. If the value is in both the array and the table, then do nothing.

What is the best way to solve this problem? It is desirable by means of Yii, when the records are presented in the form of ActiveRecord, so as not to fence the bike with multiple cycles.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Maxim, 2020-02-04
@smigles

This has nothing to do with Yii. This is common work with arrays and OOP. And how you will save (via AR, Doctrine) and where (mysql, postgresql) does not matter.
First , delete everything from the database. Then we assign new ones . Entity
example . To work with relationships in the same way as with array-objects, it is better to use yii2-save-relations-behavior

A
Anton Shamanov, 2020-02-04
@SilenceOfWinter

remove missing fields 'delete ... where value not in (...)', then replace with add/update records

D
Dmitry Kim, 2020-02-04
@kimono

You can go through behavior. Create an is_old field in the model's attribute table. Create a behavior for the model, in which to define the methods afterInsert , beforeUpdate , afterUpdate , afterDelete , and "clean" them. Next, the following logic:
afterInsert - it's clear here, insert all values ​​from the array into the database
beforeUpdate - mark all records in the database with the is_old = true
afterUpdate flag - insert values ​​from the array with the set value is_old = false, and if there is a record in the database - update is_old = false, then further delete all records from is_old = true
afterDelete- remove all values ​​from the database

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question