propelorm / Propel2

Propel2 is an open-source high-performance Object-Relational Mapping (ORM) for modern PHP
http://propelorm.org/
MIT License
1.26k stars 399 forks source link

Feature request: collection setter for entire table #1341

Open ronisaacson opened 7 years ago

ronisaacson commented 7 years ago

It would be nice to have a setter that takes a collection and does inserts/updates/deletes on a table to make it match the collection. This would be helpful when synchronizing the contents of a table with an external data source.

This code already exists for one-to-many relationship tables. For example, I can do $author->setBooks($collection_of_books) and it will make only the necessary changes. This request is to add the same functionality at the full table level, in addition to the relationship level.

marcj commented 7 years ago

Do you have an example?

ronisaacson commented 7 years ago

Think about anything you query with an API, and want to keep a local mirror of the results in your database. For example: the Sunlight Congress API lets you query a list of US Senators. But the results will change after every election. If I want to keep this list in a database table and keep it up-to-date, I can start with a list of objects:

$data = [];

$legislators = $fb->legislators->get();
foreach ($legislators["results"] as $legislator) {
  $record = new MyDatabase\Legislators();
  $record->fromArray($legislator);
  $data[] = $record;
}

Now I have $data, an array of ActiveRecord objects. I want to make the table look exactly like that array, doing any necessary insert/update/delete operations to make it happen. This is what I'm doing currently:

  1. Query for the list of records already in the database, and build an array by ID
  2. For each row in $data, look to see if the record already exists
  3. If so, then update as needed; if not, then insert
  4. Look for any row in the table that's not in $data, and delete it

This is almost the same as the logic created by Propel\Generator\Builder\Om\ObjectBuilder::addRefFKSet for any table with a one-to-many relationship. It takes a full set as input, compares to what's already there, and applies the necessary changes.

It would be nice to have this capability on the whole table.

dereuromark commented 4 years ago

Is someone able to make a PR here with suggested changes?