Framework: Ability to set fetch mode in Illuminate\Database\Query\Builder

Created on 19 Mar 2014  路  5Comments  路  Source: laravel/framework

I am in the process of building a DAL to separate my persistence layer from my logic layer, however, I am creating it as a standalone component that I can just "drop in" to another project, so can't rely on configuration.

I have been searching for a while and can not find a way to set the PDO fetch mode on a per-instance basis on Illuminate\Database\Query\Builder, meaning that I can not even rely on the returned data being an associative type, my options are:

DB::connection()->setFetchMode(PDO::FETCH_ASSOC);

Which, as far as I am aware, will set the fetch mode globally for that connection for the life time of the request, potentially modifying the behaviour of my, or somebody elses application unexpectedly.

Another option is the following:

// each function that returns results
public function fetchStuff() {
    $this->_beforeFetch();
    // fetch
    $this->_afterFetch();
}
private function _beforeFetch() {
    $this->setAppFetchMode(DB::connection()->getFetchMode());
}
private function _afterFetch() {
    DB::connection()->setFetchMode($this->getAppFetchMode());
}

Which I think you will agree is a pretty dirty hack.

All 5 comments

Indeed that is not currently possible as far as I know.

Could You please explain why it's been closed?
There is only option to store fetch_mode on the connection level which is harmful.
I used to each kind of the fetch types like column, key pair, unique, group, including its mixins and so on.
It improves workflow significantly as i don't always need to use array_column or iterate over the result set again.
Why it is so hard to handle the fetch mode on the query level?

I have been using DB::setFetchMode(PDO::FETCH_CLASS); without connection() and without any problems. FETCH_ASSOC should work the same.

@mrl22 Can you provide an example, i try to use setFetchMode() but without success.

use Illuminate\Database\Capsule\Manager as Capsule;
$db = new Capsule;
$db->setFetchMode(PDO::FETCH_CLASS);
$db->addConnection([
'driver' => 'mysql',
'host' => DB_HOST,
'database' => DB_NAME,
'username' => DB_USER,
'password' => DB_PASS,
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => DB_PREFIX,
]);
$db->setAsGlobal();

Was this page helpful?
0 / 5 - 0 ratings

Related issues

klimentLambevski picture klimentLambevski  路  3Comments

JamborJan picture JamborJan  路  3Comments

felixsanz picture felixsanz  路  3Comments

digirew picture digirew  路  3Comments

shopblocks picture shopblocks  路  3Comments