Port StdClass data to Model

天大地大妈咪最大 提交于 2019-12-06 08:36:55

问题


The problem is the following:

1) I have millions of rows in a few tables in the database, so using Eloquent is not efficient, as I have also multiple relationships. The solution in this case was to write custom DB::raw() selects and joins to accomplish the tasks efficiently. This returns a StdClass as you may know.

2) I have 4-5 models that have quite lengthy methods, which I need to use, so a best possible solution would be to create instances of those models for each row of the StdClass, and then use those methods.

Is there a known 'best practice' for 'porting' the info from the StdClass into the models, in terms of OOP patterns? How would you guys tackle this problem? I would take any suggestions, I am ready to even restructure the code.

P.S. Laravel v4.2


回答1:


Something like this will work for you. Just adjust it to your needs:

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

    // set id and other fields you want to be filled
    $this->fillable(['id', ... ]);

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

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

    $this->exists = true;

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

    return $this;
}

then you can do eg.:

$user = with(new User)->newFromStd( DB::table('users')->first() );

// or make it static if you like:
$user = User::newFromStd( DB::table('users')->first() );


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!