【问题标题】:Laravel Eloquent ORM returning stdClass instead of Model instanceLaravel Eloquent ORM 返回 stdClass 而不是 Model 实例
【发布时间】:2020-01-18 11:52:48
【问题描述】:

当我使用 eloquent 查询数据时,它会在使用 get() 函数时返回 stdClass 对象而不是我的模型实例。

$userFind = User::find(1)
$userGet  = DB::table('users')
            ->where('users.id','=', 1)
            ->select('users.*')->get()[0]

echo get_class($userFind) // -> App\User
echo get_class($userGet) // -> stdClass

Laravel Eloquent ORM returnig stdClass instead of actual Model 报告了同样的问题,但这是一个老话题,解决方案就是回到以前的 Laravel 版本。

【问题讨论】:

  • User 是 Eloquent,DB::table 是查询生成器。查询构建器不会返回 Eloquent 模型。
  • 试试$userGet = DB::table('users')->where('id', 1)->first();
  • @anyber 那么我怎样才能让用户作为模型实例并使用WHERE 子句? @AndreasHunter 谢谢,但 first() 也返回一个 stdClass 实例。
  • 你需要使用 Eloquent。 Eloquent 使用与 Query Builder 相同的方法,因此您仍然可以使用所有相同的方法。 User::find(1);User::where('id', '=', 1)->select('*')->first(); 相同来自 the docs, Since Eloquent models are query builders, you should review all of the methods available on the query builder. You may use any of these methods in your Eloquent queries.
  • @aynber 谢谢它的工作原理!

标签: php laravel eloquent model


【解决方案1】:

这是因为您使用了独立于您的模型和代码结构的\DB::table('users')。这就像直接在数据库上运行查询一样,laravel 无法知道结果是完整的 User 及其所有字段。

使用

$userGet = \App\User::query()
    ->where('id','=', 1)
    ->get()[0]
echo get_class($userGet) // -> App\User

【讨论】:

  • 你不需要query(),Eloquent 已经扩展了查询生成器。
  • @aynber 不,你不需要它,但它对 IDE 有帮助,当你从 QueryBuilder 调用方法时,Eloquent 会尝试这样做。最后,从技术上讲,自己做会更快;)
  • @aynber 和我说“尝试”,因为无论调用 $this->forwardCallTo($this->newQuery(), $method, $parameters) 和不,Eloquent\Model 不会扩展 QueryBuilder
  • 对不起,我的意思是它使用相同的方法,而不是扩展它。
  • 谢谢@N69S。由于query() 方法,我接受了这个答案,而不是@Tharaka Dilshan 的答案。我不知道它是否更快,但我觉得它更有意义。
【解决方案2】:

不是因为使用了get()method。这是因为使用了DB门面。

如果您使用模型外观进行查询,每个对象都将转换为特定的模型对象。

get()函数将返回一个Eloquent Collection而不是一个对象。

// this is a collection of users
$users = User::where('id', 1)->get();

因此,如果您想要该集合中的一个对象,您可以在它之后调用 first()
(而不是调用数组索引 [0] )。

// this one is ok too.
// but it's not recommended.
$user = User::where('id', 1)->get()[0];

// this is proper way
$user = User::where('id', 1)->get()->first();

如果您确定只有一行符合您的条件,您可以调用first() 而不是get()

$user = User::where('id', 1)->first();

【讨论】:

  • 完美!谢谢。
猜你喜欢
  • 2014-04-02
  • 1970-01-01
  • 2022-01-21
  • 2016-12-21
  • 1970-01-01
  • 2014-08-29
  • 1970-01-01
  • 1970-01-01
  • 2011-01-17
相关资源
最近更新 更多