我在Magento1中使用的是fetch_assoc()方法。我想把它转换成Magento 2。magento 2中没有fetch_assoc()方法。
if(is_object($result))
{
while ($resultsArray =$result->fetch_assoc())
{
if(empty($data))
{
$data[] = array_keys($resultsArray);
}
$data[] = $resultsArray;
} var_dump($data);
}发布于 2018-06-21 22:52:55
我不确定我提出的解决方案对您是否有用,但在Magento2中获取数据的最佳方法是基于Models和Collections。
步骤1:首先,您必须在模块中创建一个Model文件
<?php
namespace <Vendor_Name>\<Module_Name>\Model;
use Magento\Framework\Model\AbstractModel;
class Data extends AbstractModel
{
protected function _construct()
{
$this->_init('<Vendor_Name>\<Module_Name>\Model\ResourceModel\Data');
}
}第2步:在自定义模块中创建ResourceModel文件
<?php
namespace <Vendor_Name>\<Module_Name>\Model\ResourceModel;
use \Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class Data extends AbstractDb
{
protected function _construct()
{
// Second parameter is a primary key of the table
$this->_init('Table_Name', 'id');
}
}第3步:创建Collection文件以初始化Model和ResourceModel文件。
namespace <Vendor_Name>\<Module_Name>\Model\ResourceModel\Data;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
class Collection extends AbstractCollection
{
protected function _construct()
{
$this->_init(
'<Vendor_Name>\<Module_Name>\Model\Data',
'<Vendor_Name>\<Module_Name>\Model\ResourceModel\Data'
);
}
}第4步:您需要做的最后一件事是在同一模块中创建一个Block文件,并利用集合,如下所示:
namespace <Vendor_Name>\<Module_Name>\Block;
use Magento\Framework\View\Element\Template\Context;
use Magento\Framework\View\Element\Template;
use <Vendor_Name>\<Module_Name>\Model\Data as DataCollection;
class Custom_Module extends Template
{
protected $dataCollection;
public function __construct(Context $context, DataCollection $dataCollection)
{
$this->_dataCollection = $dataCollection;
parent::__construct($context);
}
public function getDataCollecton()
{
$collection = $this->_dataCollection->getCollection();
return $collection;
}
}
另一种解决方案
如果你不想实现基于models和collections的解决方案,你也可以在Magento 2中使用fetchAll代替fetch_assoc(),如下所示:
// Select Data from table
$sql = "Select * FROM " . $tableName;
$result = $connection->fetchAll($sql);作为参考,您还可以查看Magento2 – Write Custom Mysql Query (Without Using Model)
发布于 2020-03-15 22:24:17
您好,在magento 2中,您可以使用相同的,但您需要创建数据库连接。我建议你使用资源或集合模型来获得结果,如果你想以对象格式获得第一行,那么你应该使用getFirstItem();
发布于 2020-03-16 12:27:08
我认为我们可以使用下面这样的东西:
$adapter = $this->resourceConnection->getConnection($resource);
$stmt = $adapter->query($sql);
// Use FETCH_NUM so we are not dependent on the CASE attribute of the PDO connection
$results = $stmt->fetchAll(\Zend_Db::FETCH_ASSOC);或者如果我们有\Magento\Framework\DB\Adapter\AdapterInterface的$connection实例
$connection->fetchAll($sql, $binds, \PDO::FETCH_ASSOC);通过使用这些,我认为您将获得与magento 1 fetch_assoc相同的结果
https://stackoverflow.com/questions/50969207
复制相似问题