Laravel 设置数据库查询结果自动转数组

3 篇文章 0 订阅

查看官方文档:https://laravel.com/docs/5.4/upgrade

Fetch Mode
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, 按照官方文档,先引入Illuminate\Database\Events\StatementPrepared类,然后在boot方法中加入上方样例代码,最终代码如下:
<?php

namespace App\Providers;

use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;
use Illuminate\Database\Events\StatementPrepared; //引入类库 用于查询数据对象转数组 20191014

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        Registered::class => [
            SendEmailVerificationNotification::class,
        ],
    ];

    /**
     * Register any events for your application.
     *
     * @return void
     */
    public function boot()
    {
        parent::boot();

        /**
         * 这里添加对象转数组的设置 20191014
         */
        Event::listen(StatementPrepared::class, function ($event) {
            $event->statement->setFetchMode(\PDO::FETCH_ASSOC);
        });
    }
}

注意:我们设置了以关联数组的方式返回该查询结果即fetch mode设置为FETCH_ASSOC,注意,该设置只对Query Builder有效。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值