使用 Magento 标准方式编写一个 Mysql fetchAssoc()查询,以获取所有 SQL 结果行作为关联数组作为输出。
您可以使用下面的代码片段编写直接 SQL 查询fetchAssoc()而不必担心模型操作。
返回类型:fetchAssoc()总是以数组的形式返回,第一列是键,整个行数组是值。
基本功能定义:
    /**
     * Fetches all SQL result rows as an associative array.
     *
     * @param string|\Magento\Framework\DB\Select $sql An SQL SELECT statement.
     * @param mixed $bind Data to bind into SELECT placeholders.
     * @return array
     */
    public function fetchAssoc($sql, $bind = []);
 Let’s we are writing a query from sales_order table to accomplish fetchAssoc() query operation.
<?php
namespace Path\To\Class;
use Magento\Framework\App\ResourceConnection;
class fetchAssoc {
    const ORDER_TABLE = 'sales_order';
    /**
     * @var ResourceConnection
     */
    private $resourceConnection;
    public function __construct(
       ResourceConnection $resourceConnection
    ) {
       $this->resourceConnection = $resourceConnection;
    }
    /**
    * fetchAssoc Sql Query
    *
    * @return string[]
    */
    public function fetchAssocQuery()
    {
      $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->fetchAssoc($query);
      return $fetchData;
    }
}
 您需要编写一个自定义 SQL 选择查询并将该查询添加到与上述 fetchAssocQuery() 方法相同的 fetchAssoc() 函数中。
 输出: 
 在输出中,您可以看到键值始终是表的第一行值。像 1、10 和 14 是 result 的entity_id和sales_order表的第一个键。 
 这就是 fetchAssoc() 和 fetchAll() 之间的区别。 
 fetchAll 显示结果,因为键是基于 0 的值,而 fetchAssoc() 显示表中第一行的原始键值。 
Array
(
    [1] => Array
        (
            [entity_id] => 1
            [status] => pending
            [grand_total] => 334.9900
        )
    [10] => Array
        (
            [entity_id] => 10
            [status] => pending
            [grand_total] => 69.0000
        )
    [14] => Array
        (
            [entity_id] => 14
            [status] => pending
            [grand_total] => 280.0000
        )
    ...
)
			