Magento 2将自定义模型保存到数据库

时间:2018-08-21 15:03:13

标签: magento model save magento2

我正在为magento 2电子商务创建一些自定义模块; 该模块之一定义一个新模型(带有installSchema,模型本身,resourceModel和集合);

在另一个模块中,我将模型工厂注入到管理员控制器中;然后在该控制器的execute方法中,从工厂创建一个新实例,使用setData()方法设置新数据,然后保存;这里的问题是magento不会将新数据保存到DB。

这是我的文件

<?php
// --------------- Module 1 --------------
// ---------- file model -------
namespace Vendor/ModuleName/Model;
class NomeModel extends \Magento\Framework\Model\AbstractModel {
    public function __construct(
        \Magento\Framework\Model\Context $context,
        \Magento\Framework\Registry $registry,
        \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
        \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
        array $data = []
    )
    {
        parent::__construct($context, $registry, $resource, $resourceCollection, $data);
    }

    protected function _construct()
    {
        $this->_init('Vendor\ModuleNome\Model\ResourceModel\NomeModel');
    }
}

// --------------  file resource ----------
namespace Vendor\ModuleName\Model\ResourceModel;

class NomeModel extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb{
    public function __construct(
        \Magento\Framework\Model\ResourceModel\Db\Context $context
    )
    {
        parent::__construct($context);
    }

    protected function _construct()
    {
        $this->_init('nome_tabella', 'id');
    }
}
// ------------- file collection -------------
namespace Vendor\ModuleName\Model\ResourceModel\ModelName;

class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
{
    protected $_idFieldName = 'id';

    /**
     * Define resource model
     *
     * @return void
     */
    protected function _construct()
    {
        $this->_init('Vendor\ModuleName\Model\ModelName', 'Vendor\ModuleName\Model\ResourceModel\ModelName');
    }

}

// --------------------------------------------------
// ------------- module 2 ---------------------------
// ------------ controller admin --------------------
namespace Vendor\ModuleName\Controller\Adminhtml\Index;

class NomeAzione extends \Magento\Backend\App\Action {
    protected $modelloFactory
    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Vendor\ModuleName\Model\nomeModelFactory $modelloFactory
        array $data = []
    ) {
        parent::__construct($context, $data);
        [...]
        $this->modelloFactory = $modelloFactory;
    }

    public function execute(){
        $x = $this->modelloFactory->create();
        $dati = array(
            'id' => 1,
            'modello_nome' => 'nomemodello',
            'modello_info' => 'infomodello',
        );
        $x->setData($dati);
        $x->save();
        die();
    }
}

编辑:代码正确,问题出在其他文件中

0 个答案:

没有答案