Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
463 views
in Technique[技术] by (71.8m points)

php - Laravel 5.4 - How to set PDO Fetch Mode?

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) 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?

Here's an example of my code:

<?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;
    }
}

Thank you!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Go to: app/Providers/EventServiceProvider.php

Add this to the top of the file:

use IlluminateDatabaseEventsStatementPrepared;

In the boot method add:

Event::listen(StatementPrepared::class, function ($event) {
    $event->statement->setFetchMode(PDO::FETCH_ASSOC);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...