Laravel mongodb 聚合

Laravel mongodb aggregation

是否可以在原始函数中使用外部变量?

$var = 'example';
$res = DB::collection("{$var}_products")->raw(function($collection) {
        global $var; 
        return $collection->aggregate([
                ['$lookup' => [
                    'from' => "{$var}_specifications",
                    'localField' => 'specifications_id',
                    'foreignField' => '_id',
                    'as' => 'specifications'
                ]]
            ]);
        });

我只找到了一个普通的例子 SQL (https://fideloper.com/laravel-raw-queries)

$someVariable = Input::get("some_variable");
$results = DB::select( DB::raw("SELECT * FROM some_table WHERE some_col = :somevariable"), array(
   'somevariable' => $someVariable,
 ));

像这样在函数闭包中使用变量

$var = 'example';
$res = DB::collection("{$var}_products")->raw(function($collection) use ($var) {
        return $collection->aggregate([
                ['$lookup' => [
                    'from' => "{$var}_specifications",
                    'localField' => 'specifications_id',
                    'foreignField' => '_id',
                    'as' => 'specifications'
                ]]
            ]);
        });