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
Jancy Abraham
2,7148 gold badges48 silver badges76 bronze badges
-
As far as i know only u can do with for loop.Jackson– Jackson2016年12月28日 06:10:03 +00:00Commented Dec 28, 2016 at 6:10
-
But it adds only one rowJancy Abraham– Jancy Abraham2016年12月28日 06:11:43 +00:00Commented Dec 28, 2016 at 6:11
-
Follow this magento.stackexchange.com/questions/140612/…Jackson– Jackson2016年12月28日 06:15:10 +00:00Commented Dec 28, 2016 at 6:15
-
Please share your modules, complete code, also make sure your primary key should be auto increment.Arunendra– Arunendra2016年12月28日 06:23:43 +00:00Commented Dec 28, 2016 at 6:23
-
yes. primary key is auto increment. Please check the updated codeJancy Abraham– Jancy Abraham2016年12月28日 06:47:13 +00:00Commented Dec 28, 2016 at 6:47
1 Answer 1
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
Khoa Truong
32.5k11 gold badges91 silver badges159 bronze badges
default