Warning: Cannot modify header information - headers already sent by (output started at /www/wwwroot/sbboke.com/wp-content/plugins/wordpress-seo/src/integrations/front-end-integration.php:409) in /www/wwwroot/sbboke.com/wp-content/themes/pacify/content-single.php on line 5

在sql查询Magento 2中使用 fetchOne()方法

您可以使用fetchOne()方法运行直接 SQL 查询以仅获取第一个值。

fetchOne()获取 SQL 结果第一行的第一列作为输出。

您可以使用以下方式使用直接 SQL 查询获取第一行的第一列,按产品 SKU 获取产品 ID,

<?php
class UpdateQuery {
   public function __construct(
       \Magento\Framework\App\ResourceConnection $resource
   ) {
       $this->resource = $resource;
   }

   /**
    * Update Sql Query
    */
   public function runUpdateQuery()
   {
      $connection  = $this->resource->getConnection();
      $tableName = $connection->getTableName("catalog_product_entity");
      
      $select = $connection->select()->from($tableName, 'entity_id')->where('sku = :sku');
      $sku = "24-MB01";
      $bind = [':sku' => (string)$sku];

      return (int)$connection->fetchOne($select, $bind);
  }
}

Output is 1. //entity_id for SKU 24-MB01

相关文章

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