Sometimes we need to write custom insert query in magento2 as per business logic or client requirement.
In this blog, We will create some standard code to insert data using custom insert.
We need to use magento ResourceConnection class for insert data in mysql table.
Here we are adding a new record in custom table call_logs, that contains three columns only id, external_number and duration
<?php
declare(strict_types=1);
namespace MageDad\Module\Model;
use Magento\Framework\App\ResourceConnection;
class CallLogManagement
{
public function __construct(
private ResourceConnection $resourceConnection,
) { }
public function saveCallLog()
{
$data = [
'external_number' => '09876543210',
'duration' => 100
];
$connection = $this->resourceConnection->getConnection();
$tableName = $connection->getTableName('call_logs');
$connection->insert($tableName, $data);
$data = [
[
'external_number' => '09876543210',
'duration' => 100
],
[
'external_number' => '09876543211',
'duration' => 200
]
];
$connection->insertMultiple($tableName, $data);
}
}
Above code in we used insert function for single record call_logs table. We have function insertMultiple for more then one record.
I hope this blog is useful to custom insert query in magento2. In case, I missed anything or need to add some more information, Don’t heisted to leave a comment in this blog, I’ll get back with some positive approach.
Keep loving ❤️ Keep inspiring 🤩 Keep liking 👍 No sharing 😄
6 Comments
You are my intake, I possess few blogs and very sporadically run out from post :). “He who controls the past commands the future. He who commands the future conquers the past.” by George Orwell.
Hmm is anyone else having problems with the pictures on this blog loading? I’m trying to figure out if its a problem on my end or if it’s the blog. Any responses would be greatly appreciated.
As a Newbie, I am always searching online for articles that can benefit me. Thank you
I’ve been absent for some time, but now I remember why I used to love this website. Thank you, I will try and check back more frequently. How frequently you update your site?
Choose BWER for trusted weighbridge systems in Iraq, offering customized solutions to optimize your industrial operations and ensure precise weight measurement every time.
Wonderful website you have here but I was wondering if you knew of any message boards that cover the same topics discussed in this article? I’d really love to be a part of community where I can get feedback from other knowledgeable people that share the same interest. If you have any recommendations, please let me know. Thanks a lot!