Magento2 中的Fetchall() mysql查询

Mysql fetchAll()查询使用 Magento 标准方式获取自定义查询的所有记录。

您可以使用直接 SQL 查询 fetchAll() 从表中获取所有选定的记录,而无需担心模型操作。

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

基本功能定义:

/** 
* @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 fetchAll($sql, $bind = [], $fetchMode = null);

Let’s we are fetching all the record’s from sales_order table, with all the records with status equals to pending.

<?php
namespace Path\To\Class;

use Magento\Framework\App\ResourceConnection;

class fetchAllQuery {

    const ORDER_TABLE = 'sales_order';

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

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

    /**
    * fetchAll Sql Query
    *
    * @return string[]
    */
    public function fetchAllQuery()
    {
      $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->fetchAll($query);
      return $fetchData;
    }
}

Using Fetchall Output is arrays of records from a table.

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

    [1] => Array
        (
            [entity_id] => 2
            [status] => pending
            [grand_total] => 69.0000
        )

    [2] => Array
        (
            [entity_id] => 3
            [status] => pending
            [grand_total] => 280.0000
        )
)

相关文章

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