【问题标题】:Eloquent Models Returning Numeric and Associative KeysEloquent 模型返回数字和关联键
【发布时间】:2017-06-21 15:45:52
【问题描述】:

我已经使用 Laravel 5 大约两个月了,我从来没有遇到过这个框架的任何问题。到目前为止,它一直是最容易使用的框架之一,但今天开始发生一些非常奇怪的事情。这是 Laravel 5.3 的全新安装,在此安装中,我的 Eloquent 模型返回相同数据的字符串和数字键。示例如下:

型号:

class MailHeader extends Model
{
    protected $primaryKey = 'character_id';
    protected $table = 'mail_header';
    protected $fillable = [
        'character_id','mail_id','mail_subject','mail_sender','mail_sent_date','mail_labels','mail_recipient','mail_read'
    ];

}

调用检索数据:

$mail_headers = MailHeader::get();

输出:

[
        "character_id" => 95923084
        0 => 95923084
        "mail_id" => 363893745
        1 => 363893745
        "mail_subject" => "Re: XR fort office rental fee and market service, quick questions"
        2 => "Re: XR fort office rental fee and market service, quick questions"
        "mail_sender" => 94165960
        3 => 94165960
        "mail_sent_date" => "2017-01-12 18:40:00"
        4 => "2017-01-12 18:40:00"
        "mail_labels" => "{}"
        5 => "{}"
        "mail_recipient" => "{}"
        6 => "{}"
        "mail_read" => 1
        7 => 1
        "created_at" => "2017-02-04 07:51:25"
        8 => "2017-02-04 07:51:25"
        "updated_at" => "2017-02-04 07:51:25"
        9 => "2017-02-04 07:51:25"
      ]

我不知道该怎么说,但谁能帮助我。我找不到任何可能导致此问题的文档。

我可以确认Illuminate\Database\Connection.php 中的获取模式设置为PDO::FETCH_OBJ

【问题讨论】:

    标签: php mysql laravel pdo eloquent


    【解决方案1】:

    我发现了问题。

    config/database.php 中有一个名为 PDO Fetch Style 的部分。

    这部分声明了 PDO 在查询数据库时应该使用的 Fetch 类型。

    我没有这个声明,所以它在做PDO::FETCH_ALL 导致两次返回相同的数据。一次使用数字键,一次使用模型中的字符串键。

    声明本节后,返回的是一个常规数组。在下面回答。

    /*
    |--------------------------------------------------------------------------
    | PDO Fetch Style
    |--------------------------------------------------------------------------
    |
    | By default, database results will be returned as instances of the PHP
    | stdClass object; however, you may desire to retrieve records in an
    | array format for simplicity. Here you can tweak the fetch style.
    |
    */
    
    'fetch' => PDO::FETCH_OBJ,
    

    【讨论】:

      猜你喜欢
      • 2016-03-31
      • 2022-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-30
      • 2011-10-19
      • 1970-01-01
      • 2021-08-22
      相关资源
      最近更新 更多