雄辩的ORM “独立” DB::raw 失败


Eloquent ORM "standalone" DB::raw fails

对于我正在从事的项目,我使用的是Eloquent ORM独立,如本页所述。一切正常,除了我不能在我的代码中使用DB::raw。我收到以下PHP错误:

Fatal error: Class 'DB' not found

这是正确的,因为我只使用Laravel框架中的Eloquent,而不是Laravel本身。是否可以使用类似DB::raw的东西,以便我可以使用特定的SQL代码?例如where(DB::raw('YEAR(DateField)'),2013)

好吧,寻找解决方案多年,在SO上询问了它,并在互联网上的其他地方找到了答案。

Model::whereRaw('YEAR(DateField) = 2013')会做到这一点。

编辑:如果要在任何其他部分中使用DB::raw(例如在select中),则可以使用以下方法:

use Illuminate'Database'Query'Expression as raw;
// You can now use "new raw()" instead of DB::raw. For example:
$yourVar = YourModel::select(new raw("count(FieldA) AS FieldACount"),'FieldB')->groupBy('FieldB')->lists(new raw('FieldACount'),'FieldB');

我来到这里寻找如何在事务中包装自制的数据库播种器。

该函数是DB::transaction(function(){});

话虽如此,DB是一个门面。 根据Laravel Facade文档,DB同时引用了DatabaseManager和Connection。

如果您使用的是独立的 Eloquent,则需要从 Capsule 对象中获取连接。 代码最终看起来像这样:

use Illuminate'Database'Capsule'Manager as Capsule;
$capsule = new Capsule;
$capsule->addConnection([
    'driver'    => 'mysql',
    'host'      => 'localhost',
    'database'  => 'database',
    'username'  => 'root',
    'password'  => 'password',
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
]);
// Set the event dispatcher used by Eloquent models... (optional)
use Illuminate'Events'Dispatcher;
use Illuminate'Container'Container;
$capsule->setEventDispatcher(new Dispatcher(new Container));
// Make this Capsule instance available globally via static methods... (optional)
$capsule->setAsGlobal();
// Setup the Eloquent ORM... (optional; unless you've used setEventDispatcher())
$capsule->bootEloquent();
$db = $capsule->getConnection();
$db->transaction(function()
{
  // your transaction code here
});