Answer the question
In order to leave comments, you need to log in
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 | ...
Answer the question
In order to leave comments, you need to log in
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
remove missing fields 'delete ... where value not in (...)', then replace with add/update records
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 questionAsk a Question
731 491 924 answers to any question