更新时间:2023-10-19 21:46:16
先看看5.4手册中关于fetch模式的一段简述:
Laravel no longer includes the ability to customize the PDO fetch mode from your configuration files. Instead, PDO::FETCH_OBJ is always used. If you would still like to customize the fetch mode for your application you may listen for the new Illuminate\Database\Events\StatementPrepared event:
Event::listen(StatementPrepared::class, function ($event) {
$event->statement->setFetchMode(...);
});
大概意思也就是说从5.4开始, 不能再通过配置文件的方式去改变fetch mode了。而使用了事件监听设置去实现该配置。
解决方案:
打开app/Providers/EventServiceProvier.php, 按照官方文档,先引入IlluminateDatabaseEventsStatementPrepared类,然后在boot方法中加入上方样例代码,最终代码如下:
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Event;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Database\Events\StatementPrepared;
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
'App\Events\Event' => [
'App\Listeners\EventListener',
],
];
/**
* Register any events for your application.
*
* @return void
*/
public function boot()
{
parent::boot();
//
Event::listen(StatementPrepared::class, function ($event) {
$event->statement->setFetchMode(\PDO::FETCH_ASSOC);
});
}
}
楼主需要先按照手册设置这么个大前提,然后再配合toArray方法,即可达到你想要的结果。