970_90

Monday, 8 June 2015

Zend Framework How to delete a table row from foreach loop

Zend Framework How to delete a table row from foreach loop

Scenario: I have list of messages for each user. I want to delete all the messages for an particular user. Here important part is, I don't to do something with deleting each message of user.

Problem: I don't want to use the delete function which creating new query.
As I want to do something with deleting the messages, so i can't delete all record in single query.

Solution: When we list any data from model, there is inbuilt delete function which will delete the current message from foreach loop.

See Example Below
Controller Part here we write the logic
$messageObj = new Application_Model_Messages();
$id=5;
$conds = array('userId=?'=>$id, 'status=?'=>'1', );
$fields = array('id','text');
$messages=$messageObj->getMessages($conds,$fields);
foreach($messages as $message){
    $isDeleted=$message->delete(); //This will delete the current row
    if($isDeleted){
        //you can write here code when each message deleted successfully.
    }
}

here delete(), will delete the current message.

  Model Function which will list of messages of user where each message is an object (Include this function in model).
function getMessages($conds = array(),$fields=array()) {
    try {
        $select = $this->select();
        $select->from(array('m' => 'user_messages'), $fields);
        foreach ($conds as $conIndex => $condValue) {
            $select->where($conIndex, $condValue);
        } 
        $result = $this->fetchAll($select);
        if ($result) {
            return $result;
        } else {
            return FALSE;
        }
    } catch (Exception $e) {
        echo $e->getMessage();
        return FALSE;
    }
}
In this model, you can add condition and  fields dynamically. When calling you can add custom conditions and fields.

Question: How to delete one OR Multiple Record in ZF1.12?
     function deleteRecord($tourId=0) {
         return $this->delete(array('tour_id=?' => $tourId));
    }





No comments:

Post a Comment