I was trying to be down with the cool kids and use DB_Object models for a looped database update. I've found somethning I thought should work, but doesn't so I must be doing/understanding something wrong.

$bao = new CRM_Some_BAO();
$bao->hair = 'long';
while ($bao->fetch()) {
  $bao->message = 'cool hair, ' . $bao->name;

I'd thought that something like the above would find everyone with long hair and set a message to 'cool hair, <name>'

But actually what happens is that only the first match gets processed. I've also tried clone($bao) and updating the clone, but it's still same.

What's the DB_Object way of achieving such a pattern?

I'm currently just resorting to standard SQL.

  • Since you know they already exist I might try it with update() instead of save(). And while I've never tried using DB_DATAOBJECT_WHEREADD_ONLY, it seems like you might be able to omit the loop entirely and pass that param to update to be more efficient, since then it says it will do a batch update to make them all "cool" at once. – Demerit Oct 16 '19 at 15:57
  • @Demerit thanks. In trying to keep the pseudo code short I should have been clear that each update is actually unique. – artfulrobot Oct 16 '19 at 16:09
  • 1
    Ok got it. Update() alone might still work? – Demerit Oct 16 '19 at 16:13
  • @Demerit You're right, update() works, but CiviCRM's save() method does more, it also runs hooks etc. I'm looking for a generic, CiviCRM-way to do such jobs. – artfulrobot Oct 16 '19 at 16:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.