Return Laravel 中只有值(没有 keys/associative 数组)

Return values only (no keys/associative array) in Laravel

情况

我有以下代码将所有数据作为数组获取:

Data::select('id', 'text')->get()->toArray();

这将return以下格式的数据:

array:1 [
  0 => array:2 [
    "id" => "1"
    "text" => "Stack"
  ]
  1 => array:2 [
    "id" => "2"
    "text" => "Overflow"
  ]
]

但我只希望将值作为常规数组(没有 keys/associative 数组),因此当我将数组转换为 JSON:

时,数组不会转换为对象
array:1 [
  0 => array:2 [
    0 => "1"
    1 => "Stack"
  ]
  1 => array:2 [
    0 => "2"
    1 => "Overflow"
  ]
]

解决方案不充分

我知道我可以用循环转换它并使用 array_values(),但前者不是一个衬里,而第二个仅适用于一个级别而不适用于数组数组。

此外,我正在寻找 "configure" Eloquent/Query Builder 的方法,而不是转换曾经 returned 结果的方法。

问题

我可以通过 使用 Eloquent/Query Builder 执行此操作的设置或方法吗?

TL;DR

只需告诉 PDO 以这种方式工作:

DB::connection()->setFetchMode(PDO::FETCH_NUM);
Data::select('id', 'text')->get()->toArray();
DB::connection()->setFetchMode(PDO::FETCH_OBJ;);

不要忘记设置回默认值或您之前的任何设置。您还需要使用这些外观:

use DB;
use PDO;

详细(幕后)

这是通过底层 PDO 本身控制的,可以通过 fetch_style 控制。我们需要的常量是这个:

PDO::FETCH_NUM: returns an array indexed by column number as returned in your result set, starting at column 0

现在我们只需要以 Laravel 的方式传递它。在 getter:

的帮助下,此常量在 select() 函数的最后一行传递给 Illuminate/Database/Connection.php 文件中的 PDO
public function select($query, $bindings = [], $useReadPdo = true)
{
    return $this->run($query, $bindings, function ($me, $query, $bindings) use ($useReadPdo) {
        if ($me->pretending()) {
            return [];
        }

        // For select statements, we'll simply execute the query and return an array
        // of the database result set. Each element in the array will be a single
        // row from the database table, and will either be an array or objects.
        $statement = $this->getPdoForSelect($useReadPdo)->prepare($query);

        $statement->execute($me->prepareBindings($bindings));

        return $statement->fetchAll($me->getFetchMode());
    });
}

当然还有一个public setter:setFetchMode(),所以我们只需要收到连接器就可以设置它了。根据 documentation:

When using multiple connections, you may access each connection via the connection method on the DB facade.

所以我们有一切可以做到这一点:

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

方法:

DB::connection()->setFetchMode(PDO::FETCH_NUM);
Data::select('id', 'text')->get()->toArray();
DB::connection()->setFetchMode(PDO::FETCH_OBJ;);

在 laravel 5.4

之后不再是一个选项

可能的解决方法如 https://github.com/awesomedeba10 此处所建议: https://github.com/laravel/framework/issues/17557#issuecomment-536879106

您可以在配置中添加具有默认值的 .env 变量。

config/database.php:

fetch_mode => env('DB_FETCHMODE', 'FETCH_OBJ');

.env:

FETCH_MODE=FETCH_OBJ

然后在Illuminate/Database/Connection.php>准备

添加这个:

$statement->setFetchMode($config['fetch_mode'] == "FETCH_OBJ" ? 5 : ($config['fetch_mode'] == "FETCH_NUM" ? 3 : 2));

插图:

$this->fetchMode

然后你可以覆盖你的配置:

config()->set('database.connections.mysql.fetch_mode', 'FETCH_NUM');

这会保持全局默认的获取模式 FETCH_OBJ,但您仍然可以在需要时切换到 FETCH_NUM。