How do i delete data using collection in magento ORM?
Asked Answered
L

5

16

Right now i am deleting data like

  $deleteCCL = Mage::getModel('crossdata/customccitem');
  $deleteCCL->load($itemId);
  $deleteCCL->delete();

Is there any way to delete data using collection like:

$rcc = Mage::getModel('crossdata/customccitem')->getCollection()->delete();

?

Thanks a lot,

Balan

Lali answered 30/3, 2011 at 12:38 Comment(0)
P
25

There isn't a handy group delete function so either add it to your collection or simply do it directly.

foreach ($rcc as $ccitem) {
    $ccitem->delete();
}
Phippen answered 30/3, 2011 at 13:48 Comment(3)
But this would delete each individually. Wouldn't we want to be able to pipe an arbitrary collection's SQL into a DELETE so we can delete them all in one swoop?Avocation
@sparcksoft You are correct, which is why I originally said you need to "add [group delete] to your collection".Phippen
Note to self: RTF SO Answer properly :) I implemented this today, but not as generically as I would have liked. What I'd like to do is implement a delete method that you can pass an arbitrary $collection into. But I'm not exactly sure how to do it b/c the adapter delete method just takes a $where argument, and you'd need to pass in a SQL snippet that could include where's, join's, having's, group's, etc.Avocation
J
4

Mage_Eav_Model_Entity_Collection_Abstract (which extends Varien_Data_Collection_Db) provides a delete() method for collections if you have the ability to extend it.

However, it's implementation is basically the same as yours:

/**
 * Delete all the entities in the collection
 *
 * @todo make batch delete directly from collection
 */
public function delete()
{
    foreach ($this->getItems() as $k=>$item) {
        $this->getEntity()->delete($item);
        unset($this->_items[$k]);
    }
    return $this;
}
Judaica answered 2/2, 2012 at 10:57 Comment(1)
love the @todo in the docblock! :)Binocular
M
3

To implement delete functionality into a collection you have to add a new method to the collection class or a custom abstract class the collection inherits from.

Example:

public function delete()
{
    foreach ($this->getItems() as $key => $item) {
        $item->delete();
        unset($this->_items[$key]);
    }

    return $this;
}
Milissa answered 19/10, 2011 at 10:53 Comment(0)
P
1

Thanks to @leek, I got mine working:

foreach( $collection as $item )
    if( <<logic>> ) $collection->getEntity()->delete( $item );
Pournaras answered 30/7, 2012 at 23:53 Comment(0)
C
0

You can use collection walk function

Mage::getModel('crossdata/customccitem')->getCollection()->walk('delete');

or each function

Mage::getModel('crossdata/customccitem')->getCollection()->each('delete')->clear();
Circadian answered 18/1, 2023 at 8:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.