php - Laravel Eloquent ORM 返回 stdClass 而不是 Model 实例

标签 php laravel eloquent model

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

$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。

最佳答案

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

使用

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

//or simply
$userGet = \App\User::query()
    ->where('id','=', 1)
    ->first()
echo get_class($userGet) // -> App\User

关于php - Laravel Eloquent ORM 返回 stdClass 而不是 Model 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57977247/

相关文章:

phpmyadmin:如果数据最初存储为数组,则无法更改文本的值

PHP artisan 返回拒绝访问 Laravel 中的数据库连接

laravel - 如何在 Laravel 中使用 Regex 路由前缀?

php - Laravel Model函数 “create”和 “insert”有什么区别?

php - 为什么在 Eloquent 模型中调用方法时得到 'Non-static method should not be called statically'?

javascript - 循环数据表行

php上传图片并保存文件名到mysql

php - 使用来自 Controller 的未定义常量来查看

php - Laravel Eloquent 查询

php - Laravel - 将数组转换为 eloquent 集合