Dingo API,使用Database Query Builder

时间:2016-02-24 12:25:31

标签: eloquent laravel-5.2 laravel-query-builder dingo-api lumen-5.2

有谁知道我如何在Eno API中使用Eloquent Query Builder?

开箱即用Eloquent,效果很好:

use Illuminate\Database\Capsule\Manager as Capsule;

$capsule = new Capsule;
$capsule->addConnection([ ... ]);

$capsule->setAsGlobal(); // Make this Capsule instance available globally via static methods
$capsule->bootEloquent(); // Setup the Eloquent ORM

然后在我的模型中,我可以使用查询生成器:

use Illuminate\Database\Capsule\Manager as Capsule;

Capsule::table('users')->where(...)->select(Capsule::raw('AVG(rating) AS avg_rating'))->first()->avg_rating;

我知道我可以使用Eloquent获得相同的结果,但只能使用简单的查询:

User::where(..)->selectRaw(...)->first()->avg_rating;

现在使用Dingo API,当我想使用查询生成器时,我收到了以下错误消息:

Fatal error: Call to a member function connection() on null

我想这与我从未在 app / bootstrap.php 文件中调用过的 setAsGlobal 方法有关。我只有这个:

...
$app = new Laravel\Lumen\Application(
    realpath(__DIR__.'/../')
);

// $app->withFacades();

$app->withEloquent();
...

2 个答案:

答案 0 :(得分:0)

我想这是因为我使用需要照亮/数据库的流明:https://github.com/laravel/lumen-framework/blob/5.2/composer.json

但是,稳定模式下的Dingo API不需要照明/数据库。可能是原因吗?所需的包不是自动的" sub"需要吗?

答案 1 :(得分:0)

我明白了。这只是关于外墙。

取消注释 app / bootstrap.php 中的行以使用Facades:

$app->withFacades();

现在,我可以使用Facade' DB'所以查询生成器......