【问题标题】:Query returning collection of arrays instead of collection of models查询返回数组集合而不是模型集合
【发布时间】:2017-04-04 22:37:07
【问题描述】:

我使用 Laravel 5.3.31 和 PHP 7.1.2 创建了一个带有宅基地的网站。 我在远程服务器上托管了相同的站点,也使用 Laravel 5.3.31 和 PHP 7.1.3。

我的一个视图中有以下代码:

$users = \DB::table('users')->get();
dd($users);

在宅基地网站上,我得到以下结果:

Collection {#327 ▼
  #items: array:1 [▼
    0 => {#334 ▼
      +"uid": 1
      +"user_name": "test"
      +"email": "test@gmail.com"
      +"password": "somehashcode"
      +"status": "active"
      +"remember_token":  "priEYh5ewdq2IlwCwOyNc8x1w0L1zNdWHV1wLznaBfhxoWex4rDvb8lijc5T"
      +"created_at": "2017-03-20 18:30:46"
      +"updated_at": "2017-03-28 17:12:49"
    }
  ]
}

另一方面,在我的远程服务器上,我得到了这个结果:

Collection {#320 ▼
  #items: array:1 [▼
    0 => array:16 [▼
      "uid" => 1
      0 => 1
      "user_name" => "test"
      1 => "test"
      "email" => "test@gmail.com"
      2 => "test@gmail.com"
      "password" => "somehashcode"
      3 => "somehashcode"
      "status" => "active"
      4 => "active"
      "remember_token" => "WnKr77qKbgRwekZEdc9DhjLncYre5h7WvZrW7OkpOG8FZJuNFxC0CqRA5lEK"
      5 => "WnKr77qKbgRwekZEdc9DhjLncYre5h7WvZrW7OkpOG8FZJuNFxC0CqRA5lEK"
      "created_at" => null
  6 => null
  "updated_at" => "2017-04-03 19:49:50"
  7 => "2017-04-03 19:49:50"
]

] }

正因为如此,我无法在远程服务器上执行 $user->uid 并且我无法理解这可能是什么原因。有任何想法吗?这可能是 PHP 问题吗?

【问题讨论】:

  • 在另一块板上找到了解决方案。问题出在 config/database.php 文件中。它缺少 'fetch' => PDO::FETCH_OBJ 行。 laracasts.com/discuss/channels/laravel/…
  • 既然找到了解决办法,为什么不自己回答呢?

标签: php laravel-5 laravel-5.3 php-7.1


【解决方案1】:

这是一个 PDO 配置问题,我认为与此有关

config/database.php

/*
|--------------------------------------------------------------------------
| 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,

我的 database.php 文件缺少这一行。添加后,一切正常。

信用:https://laracasts.com/discuss/channels/laravel/query-returning-collection-of-arrays-instead-of-collection-of-models

【讨论】:

    猜你喜欢
    • 2023-01-02
    • 1970-01-01
    • 1970-01-01
    • 2018-12-07
    • 1970-01-01
    • 2021-02-13
    • 2012-06-16
    • 2019-10-28
    • 1970-01-01
    相关资源
    最近更新 更多