我已经使用 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
。
最佳答案
我发现了问题。
在 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,
关于php - Eloquent 模型返回数字键和关联键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42038342/