Magento 2 RAW SQL 用法
文章目录
Magento 裡面,其實已經有非常好用的 ORM 工具,內建也有 Collection 提供方便的方法來查詢,但是有時候可能還是會有需要自己寫 RAW SQL Query 的情境。那可以怎麼做呢?
Collection 方法
通常可以在 vendor/extension/model/ResourceModel/{entity_name}/ 這邊找到對應的 collection ,而 collection 的使用方法如下,這邊我們就不多作介紹。
程式碼:
<?php
// 表示要取得 customer Entity Id 等於 1 的資料
$customerCollection->addFieldToFilter('entity_id', 1)->getFirstItem();
Connection 方法
除了 Collection 之外,我們也可以使用 Connection 進行對資料庫的操作,首先透過以下程式 create 出 connection 的連線。
建立 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來幫忙。今天的介紹希望大家會喜歡。

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论