微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在 magento 2 中使用 mysql 查询获取 db 表值Magento 2 使用 sql 查询?

如何解决如何在 magento 2 中使用 mysql 查询获取 db 表值Magento 2 使用 sql 查询?

我是 Magento 的新手。

CustomModule\Database\Controller\Page\Index.PHP

<?PHP
namespace CustomModule\Database\Controller\Page;
class Index extends \Magento\Framework\App\Action\Action
{
    protected $_pageFactory;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,\Magento\Framework\View\Result\PageFactory $pageFactory)
    {
        $this->_pageFactory = $pageFactory;
        return parent::__construct($context);
    }

    public function execute()
    {
        return $this->_pageFactory->create();
    }
}

CustomModule\Database\Block\Index.PHP

<?PHP

namespace CustomModule\Database\Block;

use Magento\Framework\View\Element\Template;

class Index extends Template
{
 
    /**
     * @var \Magento\Framework\App\ResourceConnection
     */
    public $resourceConnection;
 
    public function __construct(
        \Magento\Framework\App\Action\Context $context,\Magento\Framework\App\ResourceConnection $resourceConnection
    ) {
        $this->resourceConnection = $resourceConnection;
        parent::__construct($context);
    }
 
    /**
     * Get Table name using direct query
     */
    public function getTablename($tableName)
    {
        /* Create Connection */
        $connection  = $this->resourceConnection->getConnection();
        $tableName   = $connection->getTableName($tableName);
        return $tableName;
    }
}

CustomModule\Database\view\frontend\templates\index.phtml

<?PHP
$tableName = $this->getTableName('sales_invoice_item');
$query = 'SELECT name,sku,price,qty FROM' . $tableName;
/**
 * Execute the query and store the results in $results variable
 */
$results = $this->resourceConnection->getConnection()->fetchCol($query);
echo "<pre>";print_r($results);
?>

显示错误

1 exception(s):
Exception #0 (Magento\Framework\Exception\RuntimeException): Type Error occurred when creating object: CustomModule\Database\Block\Index

Exception #0 (Magento\Framework\Exception\RuntimeException): Type Error occurred when creating object: CustomModule\Database\Block\Index
<pre>#1 Magento\Framework\ObjectManager\Factory\Dynamic\Developer->create('CustomModule\Dat...',array('data' => array())) called at [vendor\magento\framework\ObjectManager\ObjectManager.PHP:56]
#2 Magento\Framework\ObjectManager\ObjectManager->create('CustomModule\Dat...',array('data' => array())) called at [vendor\magento\framework\View\Element\BlockFactory.PHP:46]
#3 Magento\Framework\View\Element\BlockFactory->createBlock('CustomModule\Dat...',array('data' => array())) called at [vendor\magento\framework\View\Layout\Generator\Block.PHP:272]
#4 Magento\Framework\View\Layout\Generator\Block->getBlockInstance('CustomModule\Dat...',array('data' => array())) called at [vendor\magento\framework\View\Layout\Generator\Block.PHP:252]
#5 Magento\Framework\View\Layout\Generator\Block->createBlock('CustomModule\Dat...','index',array('data' => array())) called at [vendor\magento\framework\View\Layout\Generator\Block.PHP:229]
#6 Magento\Framework\View\Layout\Generator\Block->generateBlock(&Magento\Framework\View\Layout\ScheduledStructure#0000000006b3bc800000000037a2235d#,&Magento\Framework\View\Layout\Data\Structure#0000000006b3b9d10000000037a2235d#,'index') called at [vendor\magento\framework\View\Layout\Generator\Block.PHP:134]
#7 Magento\Framework\View\Layout\Generator\Block->process(&Magento\Framework\View\Layout\Reader\Context#0000000006b3b33b0000000037a2235d#,&Magento\Framework\View\Layout\Generator\Context#0000000006b3bc8d0000000037a2235d#) called at [vendor\magento\framework\View\Layout\GeneratorPool.PHP:81]
#8 Magento\Framework\View\Layout\GeneratorPool->process(&Magento\Framework\View\Layout\Reader\Context#0000000006b3b33b0000000037a2235d#,&Magento\Framework\View\Layout\Generator\Context#0000000006b3bc8d0000000037a2235d#) called at [vendor\magento\framework\View\Layout.PHP:352]
#9 Magento\Framework\View\Layout->generateElements() called at [vendor\magento\framework\Interception\Interceptor.PHP:58]
#10 Magento\Framework\View\Layout\Interceptor->___callParent('generateElements',array()) called at [vendor\magento\framework\Interception\Interceptor.PHP:138]
#11 Magento\Framework\View\Layout\Interceptor->Magento\Framework\Interception\{closure}() called at [vendor\magento\framework\Interception\Interceptor.PHP:153]
#12 Magento\Framework\View\Layout\Interceptor->___callPlugins('generateElements',array(),array(array('layout-model-cac...','core-session-dep...','customer-session...','catalog-session-...','persistent-sessi...','checkout-session...','tax-session-depe...'))) called at [generated\code\Magento\Framework\View\Layout\Interceptor.PHP:91]
#13 Magento\Framework\View\Layout\Interceptor->generateElements() called at [vendor\magento\framework\View\Layout\Builder.PHP:129]
#14 Magento\Framework\View\Layout\Builder->generateLayoutBlocks() called at [vendor\magento\framework\View\Page\Builder.PHP:55]
#15 Magento\Framework\View\Page\Builder->generateLayoutBlocks() called at [vendor\magento\framework\View\Layout\Builder.PHP:65]
#16 Magento\Framework\View\Layout\Builder->build() called at [vendor\magento\framework\View\Page\Config.PHP:224]
#17 Magento\Framework\View\Page\Config->build() called at [vendor\magento\framework\View\Page\Config.PHP:237]
#18 Magento\Framework\View\Page\Config->publicBuild() called at [generated\code\Magento\Framework\View\Page\Config\Interceptor.PHP:37]
#19 Magento\Framework\View\Page\Config\Interceptor->publicBuild() called at [vendor\magento\framework\View\Result\Page.PHP:242]
#20 Magento\Framework\View\Result\Page->render(&Magento\Framework\App\Response\Http\Interceptor#0000000006b3bbde0000000037a2235d#) called at [vendor\magento\framework\View\Result\Layout.PHP:171]
#21 Magento\Framework\View\Result\Layout->renderResult(&Magento\Framework\App\Response\Http\Interceptor#0000000006b3bbde0000000037a2235d#) called at [vendor\magento\framework\Interception\Interceptor.PHP:58]
#22 Magento\Framework\View\Result\Page\Interceptor->___callParent('renderResult',array(&Magento\Framework\App\Response\Http\Interceptor#0000000006b3bbde0000000037a2235d#)) called at [vendor\magento\framework\Interception\Interceptor.PHP:138]
#23 Magento\Framework\View\Result\Page\Interceptor->Magento\Framework\Interception\{closure}(&Magento\Framework\App\Response\Http\Interceptor#0000000006b3bbde0000000037a2235d#) called at [vendor\magento\framework\Interception\Interceptor.PHP:153]
#24 Magento\Framework\View\Result\Page\Interceptor->___callPlugins('renderResult',array(&Magento\Framework\App\Response\Http\Interceptor#0000000006b3bbde0000000037a2235d#),array(array('result-messages','result-builtin-c...','result-varnish-c...'))) called at [generated\code\Magento\Framework\View\Result\Page\Interceptor.PHP:130]
#25 Magento\Framework\View\Result\Page\Interceptor->renderResult(&Magento\Framework\App\Response\Http\Interceptor#0000000006b3bbde0000000037a2235d#) called at [vendor\magento\framework\App\Http.PHP:120]
#26 Magento\Framework\App\Http->launch() called at [generated\code\Magento\Framework\App\Http\Interceptor.PHP:24]
#27 Magento\Framework\App\Http\Interceptor->launch() called at [vendor\magento\framework\App\Bootstrap.PHP:261]
#28 Magento\Framework\App\Bootstrap->run(&Magento\Framework\App\Http\Interceptor#0000000006b3bbd70000000037a2235d#) called at [index.PHP:39]
</pre>

解决方法

简短的回答是:你没有。
Magento 2 为您提供集合和工厂来访问数据库资源,不需要您像任何现代框架那样编写任何普通的 SQL 查询。 您可以像这样将 CollectionFactory 类注入到 Classes 构造函数中:

   /** @var \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory */
   private $productCollectionFactory;

   public function __construct(\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory) {
      $this->productCollectionFactory = $productCollectionFactory;
   }

这样,您可以获得任何发票、订单、产品、产品类别等的对象表示。
但是,如果你真的需要直接运行 SQL,Amit Saini 的回答才是正确的选择。
我在上面找到了 this source

,

您可以使用以下代码通过 MySQL 查询从数据库表中获取数据:

protected $_resource;

public function __construct(
    \Magento\Framework\App\ResourceConnection $resource
) {
    $this->_resource = $resource;
}

public function execute()
{
    // get connection
    $connection     = $this->_resource->getConnection();
    // table name
    $tableName = $this->_resource->getTableName('your table name');
    // Query
    $select_sql = "Select * FROM " . $tableName;
    // fetch result
    $results = $connection->fetchAll($select_sql);
    // print result
    print_r($results);
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。