phplaravelmongodbjenssegers-mongodb

Laravel mongodb aggregation


Is it possible to use external variables inside the raw function?

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

I found only an example for an ordinary 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,
 ));

Solution

  • Use the variable inside the function closure like so

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