> For the complete documentation index, see [llms.txt](https://john-mao.gitbook.io/my-handbook/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://john-mao.gitbook.io/my-handbook/php/laravelkuang-jia/laravel-jiang-stdclass-zhuan-huan-cheng-eloquent-model.md).

# Laravel 将stdClass转换成Eloquent Model

<https://stackoverflow.com/questions/25660964/port-stdclass-data-to-model>

我们通过SQL语句执行的查询，返回的是stdClass，有时候为了方便，我们需要转换成Eloquent Model。代码：

```php
public function newFromStd(\stdClass $std){
    // backup fillable
    $fillable = $this->getFillable();

    $this->unguard(true);

    // fill $this->attributes array
    $this->fill((array) $std);

    // fill $this->original array
    $this->syncOriginal();

    $this->exists = true;

    // restore fillable
    $this->fillable($fillable);

    return $this;
}
```
