Magento 2 RAW SQL 用法

Magento 裡面,其實已經有很是好用的 ORM 工具,內建也有 Collection 提供方便的方法來查詢,可是有時候可能還是會有須要本身寫 RAW SQL Query 的情境。那能夠怎麼作呢?php

Collection 方法

一般能夠在 vendor/extension/model/ResourceModel/{entity_name}/ 這邊找到對應的 collection ,而 collection 的使用方法以下,這邊我們就很少做介紹。工具

程式碼:

<?php
      
      // 表示要取得 customer Entity Id 等於 1 的資料
      $customerCollection->addFieldToFilter('entity_id', 1)->getFirstItem();


Connection 方法

除了 Collection 以外,我們也可使用 Connection 進行對資料庫的操做,首先透過如下程式 createconnection 的連線。fetch

創建 connection

<?php
      
      //官方不建議使用 object Manager,這邊為示範用法
   $conn = $this->_objectManager->get('Magento\Framework\App\ResourceConnection')->getConnection();

select 語句

// 語句:
  // select column_name as alias_name from table_name where entity_id = '1';
  $select = $conn->select()
              ->from('table_name',
                     [
                         'column_name' => 'alias_name' ) 
                     ]
                    )
              ->where( 'entity_id = ?', '1' );

Insert 語句

$conn->insert(
              'table_name',
              [
                  'column_name_1' => 'value',
                  'column_name_2' => 'value',
              ]
          );

Update 語句

$conn->update(
      'table_name',
      [
          'field_one' => 'value1',
          'field_two' => 'value2' 
      ],
      $conn->quoteInto( 'store_id IN (?)', 'value1' )
  );

Delete 語句

<?php
  $conn->delete(
      'table_name',
      [
          'entity_id IN (?)' => $idsArray
      ]
  );

InsertOnDuplicate 語句

<?php
  $conn->insertOnDuplicate(
                  'table_name',
                  [
                      'attribute_id' => $attribute_id,
                      'entity_id' => $productId,
                      'value' => $value,
                      'store_id' => 0,
                  ],
                  [
                      'value'
                  ]
              );

取得資料

// 可使用 fetch 方法
  $result = $conn->fetchAll( $select );

  $result = $conn->fetchOne( $select );

  $result = $conn->fetchOne( $select );

  $result = $conn->fetchAssoc( $select );

  $result = $conn->fetchCol( $select );

  $result = $conn->fetchPairs( $select );

  $result = $conn->fetchRow( $select );
  • 這邊就端看使用者的需求來決定要 fetch 的種類,會回傳一個 Array 型別的資料,再用 foreach 去讀取便可


結論

  • 無論是 Collection 也好,或是 Connection 也好,都是操做資料庫的方法,沒有絕對的好壞,只有適合不適合,Collection 是封裝好的 ORM ,用起來頗為方便,可是若是是複雜的 join 語句,使用上就較為不便,還是須要靠 Connection 來幫忙。今天的介紹但願你們會喜歡。
相關文章
相關標籤/搜索