我有一个带有控制器的基本模块,并且视图工作正常。现在,我正在尝试启动模型,以便在包含属性(问题标题、问题)的表中使用自定义模型保存数据。基本上,为了通过模型将数据保存在自定义表中,我应该执行哪些步骤?
我该怎么做,任何帮助将不胜感激。
我的操作文件中有以下代码:
class Post extends \Magento\Framework\App\Action\Action
{
protected $_objectManager;
public function __construct(\Magento\Framework\ObjectManagerInterface $objectManager)
{
$this->_objectManager = $objectManager;
}
public function execute()
{
$post = $this->getRequest()->getPostValue();
$model = $this->_objectManager->create('Chirag\Mygrid\Model\Question');
$model->setData('question_title', $post['question_title']);
$model->setData('question', $post['question']);
$model->save();
}
}
<?php
/**
* Copyright © 2015 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Chirag\Mygrid\Model;
class Question extends \Magento\Framework\Model\AbstractModel
{
/**
* Initialize resource model
*
* @return void
*/
protected function _construct()
{
$this->_init('Chirag\Mygrid\Model\Resource\Question');
}
}
<?php
/**
* Copyright © 2015 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Chirag\Mygrid\Model\Resource;
class Question extends \Magento\Framework\Model\Resource\Db\AbstractDb
{
/**
* Initialize resource model
*
* @return void
*/
protected function _construct()
{
$this->_init('questions_and_answers', 'question_id');
}
}
<?php
/**
* Copyright © 2015 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Chirag\Mygrid\Model\Resource\Question;
class Collection extends \Magento\Framework\Model\Resource\Db\Collection\AbstractCollection
{
protected function _construct()
{
$this->_init('Chirag\Mygrid\Model\Question', 'Chirag\Mygrid\Model\Resource\Question');
$this->_map['fields']['page_id'] = 'main_table.page_id';
}
/**
* Prepare page's statuses.
* Available event cms_page_get_available_statuses to customize statuses.
*
* @return array
*/
public function getAvailableStatuses()
{
return [self::STATUS_ENABLED => __('Enabled'), self::STATUS_DISABLED => __('Disabled')];
}
}
第一次编辑:
我已成功完成此操作并将整个设置上传到 Git,如果您想查看,请找到以下 URL: