Laravel 将stdClass转换成Eloquent Model

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

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

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;
}

Last updated

Was this helpful?