Агрегация Laravel mongodb - PullRequest
       56

Агрегация Laravel mongodb

1 голос
/ 20 сентября 2019

Можно ли использовать внешние переменные внутри функции raw?

$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,
 ));

1 Ответ

1 голос
/ 20 сентября 2019

Используйте переменную внутри закрытия функции следующим образом:

$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'
                ]]
            ]);
        });
...