使用 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
....
)