Port StdClass数据到Model

Yas*_*vov 3 model fluent stdclass laravel eloquent

问题如下:

1)我在数据库中的几个表中有数百万行,因此使用Eloquent效率不高,因为我还有多个关系.在这种情况下,解决方案是编写自定义DB :: raw()选择和连接以有效地完成任务.如您所知,这将返回StdClass.

2)我有4-5个模型,我需要使用相当冗长的方法,因此最好的解决方案是为StdClass的每一行创建这些模型的实例,然后使用这些方法.

在OOP模式方面,是否存在将StdClass中的信息"移植"到模型中的已知"最佳实践"?你们怎么解决这个问题?我会接受任何建议,我准备甚至重组代码.

PS Laravel v4.2

Jar*_*zyk 6

这样的东西对你有用.只需根据您的需求进行调整:

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;
}
Run Code Online (Sandbox Code Playgroud)

然后你可以做例如:

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

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