How to delete the record from my custom table. without using object manager?
Example : delete from customer_comments where comments_id=124
Magento Stack Exchange is a question and answer site for users of the Magento e-Commerce platform. It only takes a minute to sign up.
Sign up to join this communityI 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());
}
}
}
$model->load($id);
is not good way. load() is @deprecated because entities must not be responsible for their own loading. Service contracts should persist entities. Use resource model "load" or collections to implement service contract model loading operations. see \Magento\Framework\Model\AbstractModel::load()
Jun 18, 2019 at 11:17