Warning: Cannot modify header information - headers already sent by (output started at /www/wwwroot/sbboke.com/wp-content/plugins/wordpress-seo/src/integrations/front-end-integration.php:409) in /www/wwwroot/sbboke.com/wp-content/themes/pacify/content-single.php on line 5

在 Magento2 中编写一个fetchPair mysql 查询

使用 Magento 标准方式编写一个 Mysql fetchPair()查询,以获取所有 SQL 结果行作为键值对数组。

您可以使用下面的代码片段编写直接 SQL 查询fetchPair()而不必担心模型操作。

返回类型:fetchPair()总是以数组的形式返回,键值对作为输出。

基本功能定义:

  /**
  * @param string|\Magento\Framework\DB\Select $sql An SQL SELECT statement.
  * @param mixed $bind Data to bind into SELECT placeholders.
  * @return array
  */
  public function fetchPairs($sql, $bind = []);

Let’s we are writing a query from sales_order table to accomplish fetchPair() query operation.

<?php
namespace Path\To\Class;

use Magento\Framework\App\ResourceConnection;

class fetchPair {

    const ORDER_TABLE = 'sales_order';

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

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

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

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

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

Output:
Here in output, you can see key value is entity_id and value as the status of the order.

Array
(
    [1] => pending
    [12] => pending
    [20] => pending
    ....
)

相关文章

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