回归数字和关联密钥的雄辩模型

时间:2017-02-04 08:45:02

标签: php mysql laravel pdo eloquent

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

型号:

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

1 个答案:

答案 0 :(得分: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,