Laravel 5.4 - 如何设置 PDO 获取模式?

Laravel 5.4 - How to set PDO Fetch Mode?(Laravel 5.4 - 如何设置 PDO 获取模式?)
本文介绍了Laravel 5.4 - 如何设置 PDO 获取模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

自定义获取模式的功能已从 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 获取模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)