I want to delete rows from Database without for loop to increase efficiency

I had done with the code having loop.Below are snippets for the same :

$collections = $model->getCollection()
                 ->addFieldToFilter('customers_id', array('eq' => '139'))
foreach ($collections->getData()  as $value) {
                $data = Mage::getModel('save/save')->load($value['id']);

I want to delete data having customers_id = 139 Note:customers_id is not my primary key

Can Any one help me out ?


You can always use direct custom queries in Magento.

    /** @var Mage_Core_Model_Resource $resource */
    $resource = Mage::getSingleton('core/resource');
    /* @var $writeConnection Magento_Db_Adapter_Pdo_Mysql */
    $writeConnection = $resource->getConnection('core_write');

    $query = "DELETE FROM `table_save_save` WHERE `customer_id` = '139';";
    $result = $writeConnection->query($query);

However, always keep in mind that this might not be the best solution. It depends on the fact if you have table relations to this custom table and if it's provided with triggers or not.

If it's not the case and you don't delete object via a collection, you might miss out on important functions which are triggered before or after the delete function on an object.

Keep in mind that this solution (code above) is not really good. You'll want to used bindings in your query to avoid SQL-injection.

| improve this answer | |
  • But there is no way to do it without custom queries ? – Hetal1311 Sep 24 '18 at 12:56
  • 1
    It depends on which collection you're working with but to increase performance, you could try and work with an iterator and don't load the object before deleting it. Like this: $collection->walk('delete'); – haroldclaus Sep 24 '18 at 13:14
  • It is not best way.. – alexey boltynov Sep 24 '18 at 17:31
  • @alexeyboltynov > That is what I said. It is not the best solution. The best solution is to optimise your collection and delete it via the entity itself. – haroldclaus Sep 25 '18 at 6:08
  • how to get table which have prefix? – jafar pinjar Jan 10 at 7:05

Try this.

$model = Mage::getModel('your model');

$id=139;// you can insert  dynamically 

->addFieldToFilter('customers_id', $id)
| improve this answer | |
  • You can use if() , for checking value of user id . – alexey boltynov Sep 24 '18 at 17:41
  • Call to undefined method Cart_Save_Model_Mysql4_Save_Collection::delete() Facing above error while trying your code – Hetal1311 Sep 25 '18 at 9:39
  • Try $model->getCollection() ->addFieldToFilter('customers_id', $id) – alexey boltynov Sep 25 '18 at 19:33
  • $model->delete(); – alexey boltynov Sep 25 '18 at 19:34
  • $model-> save(); – alexey boltynov Sep 25 '18 at 19:34

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.