Search code examples
symfony1symfony-1.4propel

Update multiple rows with Propel 1.4


I need to execute following query (Using Propel 1.4/Symfony 1.4)

update notification
set read=1
where to=6 AND
    action=0

For this, I wrote following code in symfony 1.4

$c=new Criteria()
$c->add(NotificationPeer::TO, $memberId, Criteria::EQUAL);
$c->add(NotificationPeer::ACTION, 0, Criteria::EQUAL);
$notification = NotificationPeer::doSelect($c);

foreach($notification as $notice)
{
    $notice->setRead(1);
    $notice->save();
}

Its working but if there are 100's of notification for any user, it will cost 100s of query and unnecessary load to server. I looked on doUpdate method of propel, I guess it can work for me but unable to figure out how.

IS there any way (I know there is but I don't know it) to do all that stuff in single query?


Solution

  • You should build two criteria:

    • one for the where clause
    • the other one for the update clause.
    // Build WHERE criteria
    $wherec = new Criteria();
    $wherec->add(NotificationPeer::TO, $memberId, Criteria::EQUAL);
    $wherec->add(NotificationPeer::ACTION, 0, Criteria::EQUAL);
    
    // Build updated field criteria
    $updc = new Criteria();
    $updc->add(NotificationPeer::READ, 1);
    
    BasePeer::doUpdate($wherec, $updc, $con);
    

    It performs one (could be big) query. See this snippet.