문제

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?

도움이 되었습니까?

해결책 2

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.

다른 팁

Try using update all insted

$update = array();
$update['title'] = 'my first book';
$update['author'] = 'Danny DeVito' ;

$book[0]->update_all(array('set' =>$update));
$book[4]->update_all(array('set' =>array("title"=>"Nice Title"));

I think this should be cleaner

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top