Laravel 4-在运行时设置database.fetch配置 [英] Laravel 4 - set database.fetch config at runtime

查看:251
本文介绍了Laravel 4-在运行时设置database.fetch配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Laravel 3中,我可以在运行时设置数据库获取"配置(以数组而不是对象的形式获取结果):

In Laravel 3 I could set the database 'fetch' config at runtime (to get the results as an array rather than an object):

Config::set('database.fetch', PDO::FETCH_ASSOC);

在Laravel 4中,结果仍作为对象返回.

In Laravel 4, the result is still being returned as an object.

我在做什么错了?

我决定测试是否已设置配置,并尝试并排尝试Laravel 3和Laravel 4中相同的代码段.

I decided to test if the config was being set, and also to try identical code segments in Laravel 3 and Laravel 4 side-by-side.

//first fetch as object
Config::set('database.fetch', PDO::FETCH_CLASS);
//Laravel 3 and 4 returns 88 ... expected:
echo PDO::FETCH_CLASS.Config::get('database.fetch');
$users = $users = DB::table('users')->get();
//Laravel 3 and 4 both return an array of objects(stdClass) ... expected
var_dump($users);

//then fetch as array
Config::set('database.fetch', PDO::FETCH_ASSOC);
//Laravel 3 and 4 returns 22 ... expected:
echo PDO::FETCH_ASSOC.Config::get('database.fetch');
$users = $users = DB::table('users')->get();
//Laravel 3 returns an array of arrays ... expected
//Laravel 4 returns an array of objects(stdClass) ... UNEXPECTED!
var_dump($users);

推荐答案

TL; DR:不要将config用于运行时更改

配置集是初始化时仅获取 的方式.通常对于所有Illuminate库都是如此.

TL;DR: Don't use config for run-time changes

The configuration set's the fetch mode on initialization only. This is generally true for all Illuminate libraries.

如果需要在运行时中更改获取模式,则需要在连接对象而不是配置中进行设置.

If you need to change the fetch-mode in run-time, you need to set this on your connection object rather than in the configuration.

幸运的是,我们可以访问连接对象.

Luckily, we have access to the connection object.

请注意,Connection对象具有 setFetchMode() 方法.

Notice that the Connection object has a setFetchMode() method.

这意味着在您的代码中,您可以获得连接,然后在查询之前先运行setFetchMode(PDO::FETCH_ASSOC)数据库.

This means in your code you can get your connection and then run setFetchMode(PDO::FETCH_ASSOC) with it prior to querying the DB.

// With Query Builder
$query = DB::connection()->setFetchMode(PDO::FETCH_ASSOC);

// With Eloquent model
$user = new User;
$user->getConnection()->setFetchMode(PDO::FETCH_ASSOC);

这篇关于Laravel 4-在运行时设置database.fetch配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆