問題描述
自定義獲取模式的功能已從 L5.4 中刪除,默認為 PDO::FETCH_OBJ.
The ability to customize the fetch mode was removed from L5.4 and is defaulted to PDO::FETCH_OBJ.
升級指南指出您可以使用事件偵聽器覆蓋它:
The upgrade guide states that you can override this by using an event listener:
Event::listen(StatementPrepared::class, function ($event) {
$event->statement->setFetchMode(...);
});
我一生都無法理解如何實現這一點:
I can't for the life of me understand how to implement this:
1) 我應該把代碼放在哪里?我應該使用 EventServiceProvider
注冊它嗎?
2) StatementPrepared
事件何時觸發?(我只需要為特定的存儲庫功能更改 Fetch Mode,而不是在全局范圍內).
3) FetchMode 是否會為后續查詢自動恢復?
1) Where should I place the code? Should I register it with the EventServiceProvider
?
2) When does the StatementPrepared
event fire? (I only need to change the Fetch Mode for specific repository functions, not on a global scale).
3) Does the FetchMode revert itself automatically for subsequent queries?
這是我的代碼示例:
<?php
namespace AppRepositoriesBackend;
use DB;
use PDO;
class SystemRepository
{
/**
* Get the connection status variables.
*
* @return array
*/
public function getConnectionStatus()
{
DB::connection('backend')->setFetchMode(PDO::FETCH_ASSOC);
$result = DB::connection('backend')
->select(DB::raw("
SHOW STATUS
WHERE Variable_name = 'Max_used_connections'
OR Variable_name = 'Max_used_connections_time'
OR Variable_name = 'Threads_connected'
"))
;
DB::connection('backend')->setFetchMode(PDO::FETCH_CLASS);
return $result;
}
}
謝謝!
推薦答案
轉到:app/Providers/EventServiceProvider.php
將此添加到文件頂部:
use IlluminateDatabaseEventsStatementPrepared;
在 boot 方法中添加:
Event::listen(StatementPrepared::class, function ($event) {
$event->statement->setFetchMode(PDO::FETCH_ASSOC);
});
這篇關于Laravel 5.4 - 如何設置 PDO 獲取模式?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!