通常,您可以通过将 PDO 语句 fetch_style 设置为 PDO::FETCH_CLASS 来实现这一点,如下所示
$statement->fetchAll(PDO::FETCH_CLASS, "App\User");
如果您查看Illuminate\Database\Connection::select 方法,您会发现虽然您可以设置 fetch_style/fetchMode,但不能设置第二个参数。
public function select($query, $bindings = array(), $useReadPdo = true)
{
return $this->run($query, $bindings, function($me, $query, $bindings) use ($useReadPdo)
{
if ($me->pretending()) return array();
// For select statements, we'll simply execute the query and return an array
// of the database result set. Each element in the array will be a single
// row from the database table, and will either be an array or objects.
$statement = $this->getPdoForSelect($useReadPdo)->prepare($query);
$statement->execute($me->prepareBindings($bindings));
return $statement->fetchAll($me->getFetchMode());
});
}
例如,在调用 fetchAll 以调用 PDOStatement::setFetchMode 之前,您也无法访问该语句。
您或许可以尝试扩展 Illuminate\Database\Connection,并通过在必要时扩展和替换来在其他与数据库相关的类中使用它,但维护起来似乎是一项艰巨的任务。
另一种选择是使用 Eloquent,它会为您提供特定类型的类,但您会获得一些额外的水合模型对象的开销。
class Foo extends Illuminate\Database\Eloquent\Model {
protected $table = 'foo';
}
Foo::all()
Foo::where('col', 1)->get()