Search code examples
phpdatabaseactiverecordphpactiverecord

PHP Activerecord: updating array of objects


The following code will return an array of PHP Activerecord Objects:

$book = Book::find('all');

Assuming the program is aware of the order of books I can continue and update the attributes of the books and save them to the database as follows:

$book[0]->title = 'my first book';
$book[0]->author = 'Danny DeVito';
$book[4]->title = 'Nice Title';

in order to save the above I would have to invoke the ->save() method on each object

$book[0]->save();
$book[4]->save();

  1. Is there a better way to do this? built-in PHP ActiveRecord function that saves all members of a given array of objects, or based on an association?

  2. Assuming the original title of $book[4] above was already 'Nice Title', would the ->save() method consider $book[4]changed and continue with the database save?


Solution

  • After much research I decided to post my conclusions/answers:

    There is no such ActiveRecord library function that can update an array of objects with unique values.

    Assuming Activerecord would shoot one update request it would look like this:

    UPDATE books
       SET title = CASE id
          WHEN 0 THEN 'my first book'
          WHEN 4 THEN 'Nice Title'
       END,
       author = CASE id
          WHEN 0 THEN 'Danny DeVito'
       END
    WHERE id IN (0,4)
    

    The same question as "how would I update multiple rows with different values at once". This would go against the design of an Activerecord model, as an Object represents a row, and maps rows across tables. An obvious limitation for having such an easy model to work with.

    Any assignment to an Object's attributes triggers a 'dirty' flag on that attribute, and any subsequent call to update/save that object will trigger a query even if the assigned attribute value is the same as the database/model's previous value. Invoking the save() method when no assignments were made does not trigger this query.