在Magento2 中编写一个 fetchCol()Sql查询

使用 Magento 标准方式编写 Mysql fetchCol()查询而不使用模型文件,以获取所有 SQL 结果行的第一列作为数组。

返回类型: fetchCol() 总是以数组的形式返回。

基本定义:

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

Let’s write a query from the sales_order table to accomplish fetchCol() query operation.

<?php
namespace Path\To\Class;

use Magento\Framework\App\ResourceConnection;

class FetchCol {

    const ORDER_TABLE = 'sales_order';

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

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

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

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

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

Output:
An Array result with value is entity_id of sales_order table.

Array
(
    [1] => 15
    [2] => 17
    [3] => 19
    ....
)

15, 17 and 19 is the entity_id with pending status.

相关文章

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