【发布时间】: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