Magento 2将数据插入数据库 [英] Magento 2 insert data into database

查看:348
本文介绍了Magento 2将数据插入数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近在Magento 2中创建了一个模块.现在我从数据库的前端phtml文件中获取数据.代码如下.

I recently created a module in Magento 2. Now I get the data from the database in front-end phtml file.The code is given below.

 try
{
    $question = $this->_objectManager->create('Magecomp\Firstmodule\Model\Firstmodule');
    $question->setTitle('SimpleQuestion');
    $question->save();
}
catch(Exception $e)
{
     echo $e->getMessage();
}

但我收到以下错误消息:

But I get following Error :

 Notice: Undefined property: Magecomp\FirstModule\Block\FirstModule::$_objectManager in C:\xampp\htdocs\magento2\lib\internal\Magento\Framework\View\TemplateEngine\Php.php on line 113

请帮助我获取模型对象,然后将数据插入表中.

Please help me to get the object of model and then insert data into table.

推荐答案

这是我的索引操作代码,在其中我创建了objectManagger对象,并使用objectManager成功将数据添加到数据库中.

This is my index action code in which i create a object of objectManagger and successfully add data into database using objectManager.

namespace Test\Firstmodule\Controller\Index;
class Index extends \Magento\Framework\App\Action\Action
{

    public function execute()
   {
        $model = $this->_objectManager->create('Test\FirstModule\Model\Firstmodule');
        $model->setTitle('What is Question ?');
        $model->save();
        $this->_view->loadLayout();
        $this->_view->getLayout()->initMessages();
        $this->_view->renderLayout();
   }
}

这篇关于Magento 2将数据插入数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆