Magento, Magento 2

How to Use the fetchOne() method with SQL query in Magento 2

How to Use the fetchOne() method with SQL query in Magento 2

In this tutorial, Today I will explain to you how to use the fetchOne() method with SQL Query in Magento 2. There are many times we need to require to perform operation on data by SQL Query. fetchOne() method is used to fetch first column of the first row of the SQL query output.

You may also like this :

Here, I am explain to you with example.

Step to How to Use the fetchOne() method with SQL query

<?php
/**
 * Created By : Rohan Hapani
 */
namespace RH\Helloworld\Model\ResourceModel;

use Magento\Framework\App\ResourceConnection;

class FetchOneRecordData
{
    /**
     * @var ResourceConnection
     */
    private $resourceConnection;

    /**
     * @param ResourceConnection $resourceConnection
     */
    public function __construct(
        ResourceConnection $resourceConnection
    ) {
        $this->resourceConnection = $resourceConnection;
    }

    /**
     * Select query to fetch single column's first value
     *
     * @return array
     */
    public function getOneValueQuery()
    {
        $tableName = $this->resourceConnection->getTableName('catalog_product_entity');
        $connection = $this->resourceConnection->getConnection();
        $sku = '24-MB01';

        $select = $connection->select()
            ->from(
                ['c' => $tableName],
                ['*']
            )
            ->where(
                "c.sku = :sku"
            );
        $bind = ['sku' => $sku];

        return $connection->fetchOne($select, $bind);
    }
}

In the above query, [‘*’] means Fetching all the fields of the table. If you want to fetch specific field then, you just need to add fields with comma separated.

Here, $sku value to the bind array instead of directly passing the value to the given where conditions. Using this fetchOne() you will get first value of the first column record. So, as per that you will get entity_id of this record.

That’s it !!!

I hope this blog is easy to understand about how to use the fetchOne() method with SQL Query in Magento 2. In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with proper solution.

Keep liking and sharing !!

Tagged ,