Laravel 5.4 - How to set PDO selection mode?

The ability to configure the fetch mode was removed from L5.4 and the default command PDO :: FETCH_OBJ was set.

The upgrade guide states that you can override this using an event listener:

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

I can’t understand in life how to implement this:

1) Where should I put the code? Should I register it using EventServiceProvider ?
2) When does the StatementPrepared event fire? (I need to change the Fetch mode for specific repository functions, not globally).
3) Does FetchM automatically return automatically for subsequent requests?

Here is an example of my code:

 <?php namespace App\Repositories\Backend; 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; } } 

Thanks!

+7
source share
4 answers

Go to: app / Providers / EventServiceProvider.php

Add this to the top of the file:

 use Illuminate\Database\Events\StatementPrepared; 

In the boot method add:

 Event::listen(StatementPrepared::class, function ($event) { $event->statement->setFetchMode(\PDO::FETCH_ASSOC); }); 
+5
source
 $dbh=DB::getPdo(); $sth = $dbh->prepare("SHOW STATUS WHERE Variable_name = 'Max_used_connections' OR Variable_name = 'Max_used_connections_time' OR Variable_name = 'Threads_connected' "); $sth->execute(); $result = $sth->fetch(PDO::FETCH_CLASS); print_r($result); 

Try it. worked for me. You only need the DB trait (use the DB;).

0
source

Add default fetch mode to config / database.php

 return [ 'fetch' => PDO::FETCH_CLASS, ... ]; 
0
source

There is another option to find it past Add env DB_FETCHMODE=FETCH_ASSOC
In config / database add for connection.mysql 'fetch_mode' => env('DB_FETCHMODE', 'FETCH_ASSOC'),
In the highlighting /datbase/connection.php replace the prepared function with
protected function prepared (PDOStatement $statement){ $config = $this->config; $statement->setFetchMode($config['fetch_mode'] == "FETCH_OBJ" ? 5 : ($config['fetch_mode'] == "FETCH_NUM" ? 3 : 2)); $this->event(new Events\StatementPrepared( $this, $statement )); return $statement; }

This makes the default FETCH_ASSOC for your application

Then, if you want to change it as before, add
config(['database.connections.mysql.fetch_mode' => 'FETCH_OBJ']);
replacement DB::setFetchMode(PDO::FETCH_ASSOC);

0
source

All Articles