Magento 2 : How to delete the record in custom table?
-
09-10-2020 - |
Question
How to delete the record from my custom table. without using object manager?
Example : delete from customer_comments where comments_id=124
Solution
I think the best way just follow Magento standard. For example just check Cms magento module.
So you have a new module app/code/MyCompany/MyModule
Model/Comment.php
namespace MyCompany\MyModule\Model;
class Comment extends \Magento\Framework\Model\AbstractModel {
/**
* @var string
*/
protected $_cacheTag = 'customer_comment';
/**
* @var string
*/
protected $_eventPrefix = 'customer_comment';
/**
* @return void
*/
protected function _construct()
{
$this->_init(\MyCompany\MyModule\Model\ResourceModel\Comment::class);
}
}
Model/ResourceModel/Comment.php
namespace MyCompany\MyModule\Model\ResourceModel;
class Comment extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb {
/**
* Initialize resource model
*
* @return void
*/
protected function _construct()
{
$this->_init('you_custom_table_name', 'comment_id');
}
}
Controller/Comment/Delete.php
namespace MyCompany\MyModule\Controller\Comment;
use MyCompany\MyModule\Model\CommentFactory;
class Delete extends \Magento\Framework\App\Action\Action {
/**
* @var CommentFactory
*/
protected $_commentFactory;
protected $messageManager;
/**
* @param \Magento\Framework\App\Action\Context $context
* @param CommentFactory $commentFactory
*/
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Framework\Message\ManagerInterface $messageManager,
CommentFactory $commentFactory
) {
$this->_commentFactory = $commentFactory;
$this->messageManager = $messageManager;
parent::__construct($context);
}
public function execute()
{
$id = $this->getRequest()->getParam('comment_id');
try {
$model = $this->_commentFactory->create();
$model->load($id);
$model->delete();
} catch (\Exception $e) {
$this->messageManager->addError($e->getMessage());
}
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange