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)

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;      


        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;                                  
            return $resultRedirect->setPath('*/*/new');


Please help me


We forgot to unset data model after saving.



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();
| improve this answer | |

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.