7

I have created a new table in Magento2: my_custom_table with 4 fields:

id: primary key, 
product_id: int(11), 
customer_id: int(11)
status:int(11)

I want to save multiple records at a time. Here is my code.

namespace Company\Module\Controller\Adminhtml\Index;    

class Save extends \Company\Module\Controller\Adminhtml\Index
    {

        protected $_filterProvider;
        protected $productModel;


        public function __construct(
            \Magento\Backend\App\Action\Context $context,
            \Magento\Framework\Registry $registry,
            \Magento\Cms\Model\Template\FilterProvider $filterProvider,
            \Company\Module\Model\Product  $productModel

        ) {
            $this->_filterProvider = $filterProvider;
            $this->productModel = $productModel;      

            parent::__construct($context,$registry);
        }

        public function execute()
        {
            $resultRedirect = $this->resultRedirectFactory->create();
            $data = $this->getRequest()->getPostValue();
            if ($data) {
                $products = array(12,13,14,14);
                $customerId = 1;
                foreach($products as $pdt){
                    $productModel = $this->productModel;                                  
                    $productModel->setData('product_id',$pdt);
                    $productModel->setData('customer_id',$customerId);
                    $productModel->setData('product_status',1);
                    $productModel->save();
                }
            }
            return $resultRedirect->setPath('*/*/new');
        }

    }  

Please help me

10

We forgot to unset data model after saving.

$productModel->save();
$productModel->unsetData();

[EDIT]

Using model Factory can solve our issue. For example, inject Company\Module\Model\ProductFactory in constructor . Inside the loop, we just need to create the factory.

$product = $this->productFactory->create();
$product->setData(....);
$product->save();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.