Magento – Why delete() Function Is Not Deleting Value After Filtering Collection

adminmagento-1.7module

I am trying to delete a data from the table.

I am using this code snippet

$categoryModel= Mage::getModel('blog/category')
        ->getCollection()
        foreach ($categoryModel as $cat) {  
                $cat->delete();
        }

and it is deleting the complete table.

but I dont want to delete the complete table so I filter the data with some attribute and tried this code

$categoryModel= Mage::getModel('blog/category')
        ->getCollection()
        ->addFieldToFilter('article_id', $articleId);  
        foreach ($categoryModel as $cat) {
                $cat->delete();
        }

but it is not deleting anything.
How can I delete the data according to some field.

Best Answer

Your addFieldToFilter method is incorrect, you need to type:

$categoryModel= Mage::getModel('blog/category')
    ->getCollection()
    ->addFieldToFilter('article_id', array('eq'=>$articleId));  
    foreach ($categoryModel as $cat) {
            $cat->delete();
    }

Or as an alternative, you could go the direct SQL route:

public function delete_articles($article_id_value){
    $connection = $this->_getConnection('core_write');
    $table = $this->_getTableName('my_table_name');
    $sql = 'DELETE FROM ' . $table . ' WHERE `article_id` = ?';
    $connection->query($sql, $article_id_value);
}

public function _getConnection($type = 'core_read'){
    return Mage::getSingleton('core/resource')->getConnection($type);
}

public function _getTableName($tableName){
    return Mage::getSingleton('core/resource')->getTableName($tableName);
}