9

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

asked Dec 28, 2016 at 6:05
6
  • As far as i know only u can do with for loop. Commented Dec 28, 2016 at 6:10
  • But it adds only one row Commented Dec 28, 2016 at 6:11
  • Follow this magento.stackexchange.com/questions/140612/… Commented Dec 28, 2016 at 6:15
  • Please share your modules, complete code, also make sure your primary key should be auto increment. Commented Dec 28, 2016 at 6:23
  • yes. primary key is auto increment. Please check the updated code Commented Dec 28, 2016 at 6:47

1 Answer 1

12

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();
answered Dec 28, 2016 at 8:25

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.