0

I am trying to delete a record in my custom table (custom model). I can do it like this:

$mymodel = $this->mycustomFactory->create();
$mymodel->load($id);
$mymodel->delete();
    

But I need to specify two fields to load by:

$id & $customerId

In MySQL it would something like:

DELETE FROM mycustomtable where id = $id AND customer_id = $customerId;

But I only want to delete this record, not load it fully.

How can I achieve this?

2
  • you need to use collection filter over there by those 2 fields. Sep 9, 2021 at 13:17
  • If you dont want to load them and it's a custom model just... execute the query instead of loading the collection Sep 9, 2021 at 15:59

2 Answers 2

1

As I didn't want to use direct SQL I ended up creating a collection and then looping through and deleting:

$myCollection = $this->myCollectionFactory->create()
    ->addFieldToFilter('attr1', array('eq'=> 'aaa')
    ->addFieldToFilter('attr2', array('eq'=> 'bbb'))
    ->addFieldToFilter('attr3', array('eq'=> 'ccc'));

$myModelFactory = $this->myModelFactory->create();
foreach ($myCollection as $myModel) {
    $myModelFactory->load($myModel->getId());
    $myModelFactory->delete();
}

Not sure if this is the correct way but it works. Thanks.

0
           $customModel= $this->customModel->create();
            $customModelClone = $customModel->getCollection()->addFieldToSelect('*')
                ->addFieldToFilter('coupon_code',['like' => "$othervar%"]);
                
            if ($sku == null) {
                $customModelClone;
            } else {
                $customModelClone->addFieldToFilter('sku',['eq' => $sku]);
            }

            if ($customModelClone->getSize() > 0) {
                foreach ($customModelClone  as $custom) {
                    $custom->delete();
                }
            }

for me in magento 2.4.3 use Company\CustomModule\Model\ModelFactory, if use load() it will fail, but if you not use load() and foreach after addFieldToFilter() it will be successfully removed (able to multiple data)

I hope this helps

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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