在Magento 2 中编写一个fetchRow直接mysql查询

使用 Magento 标准方式编写一个 Mysql fetchRow()查询,用于获取 SQL 结果的第一行作为输出。

您可以使用查询从结果数组列表中获取第一行作为结果。

直接 SQL 查询 fetchRow() 而不用担心 Model 操作。

返回类型: fetchRow() 始终根据您的查询条件返回为数组。

基本功能定义:

     /**
     * Fetches the first row of the SQL result.
     *
     * Uses the current fetchMode for the adapter.
     *
     * @param string|\Magento\Framework\DB\Select $sql An SQL SELECT statement.
     * @param mixed $bind Data to bind into SELECT placeholders.
     * @param mixed $fetchMode Override current fetch mode.
     * @return array
     */
    public function fetchRow($sql, $bind = [], $fetchMode = null);

Let’s we are fetching the first row from sales_order table.

<?php
namespace Path\To\Class;

use Magento\Framework\App\ResourceConnection;

class FetchRow {

    const ORDER_TABLE = 'sales_order';

    /**
     * @var ResourceConnection
     */
    private $resourceConnection;

    public function __construct(
       ResourceConnection $resourceConnection
    ) {
       $this->resourceConnection = $resourceConnection;
    }

    /**
    * fetchRow Sql Query
    *
    * @return string[]
    */
    public function fetchRowQuery()
    {
      $connection  = $this->resourceConnection->getConnection();
      $tableName = $connection->getTableName(self::ORDER_TABLE);

      $query = $connection->select()
        ->from($tableName,['entity_id','status','grand_total'])
        ->where('status = ?', 'pending');

      $fetchData = $connection->fetchRow($query);
      return $fetchData;
    }
}

We are fetching the first row from the sales_order table with Order status is pending.

The output is the first row of the SQL result as an array.

Array
(
    [0] => Array
        (
            [entity_id] => 1
            [status] => pending
            [grand_total] => 1299.0000
        )
)

相关文章

0 0 投票数
文章评分
订阅评论
提醒
0 评论
内联反馈
查看所有评论