问题如下:
1) 我在数据库中的几个表中有数百万行,所以使用Eloquent并不高效,因为我还有多个关系。这种情况下的解决方案是编写自定义DB::raw()选择和联接,以高效地完成任务。如您所知,这将返回一个StdClass。
2) 我有4-5个模型有相当长的方法,我需要使用这些方法,所以最好的解决方案是为StdClass的每一行创建这些模型的实例,然后使用这些方法。
在OOP模式方面,是否有已知的将StdClass中的信息"移植"到模型中的"最佳实践"?你们将如何解决这个问题?我会接受任何建议,我甚至准备重组代码。
p.S.Laravel v4.2
这样的东西对你有用。只需根据您的需求进行调整:
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;
}
然后你可以做例如:
$user = with(new User)->newFromStd( DB::table('users')->first() );
// or make it static if you like:
$user = User::newFromStd( DB::table('users')->first() );