how to pass variables “$tid, $id” into raw functio

2019-08-05 16:42发布

问题:

when i call $id and $tid in raw function to fetch some data from sub document of mongodb collection it show me an error these two variables are undefined($tid,$id)?

<?php
$id=IntValue;
$tId=IntValue;
if($tId==0)
{
    $maxPlayers=0;
}
else
{
  $result = DB::collection('PrizeDistributionTemplate')->raw(function($collection)
        {

            return $collection->aggregate(array(
                array(
                    '$match' => array( 'id' => $id,'templates.tId' => $tid)
                ),
                array( '$unwind' => '$templates' ),
                array(
                    '$match' => array( 'id' => $id,'templates.tId' => $tid)
                ),
            ));       
        });

  $result=json_decode(json_encode($result),true);
  $maxPlayers=$result['result'][0]['templates']['maxPlayers'];
  $maxPlayers=intval($maxPlayers)+2;
}
?>

回答1:

It will work great with bulk addition, this way you just need to create on array and pass it.

$temp = [
   [
     'item' => "envelopes"
   ],
   [
     'item' => "envelopesas"
   ],
   [
     'item' => "lala"
   ]
 ];

 $userData = DB::table('log') - > raw(function ($collection) use($temp) 
 {

   return $collection - > insertMany($temp);
 });


回答2:

When you use a callback function in PHP, the function as it own scope and can't access variables from outside of it's scope.

$foo = true;

DB::collection('something')->raw(function ($collection) {
    echo $foo;// $foo is undefined here, this create an error
});

echo $foo;// here it work

But you can feed your callback with variables using the PHP use keyword:

$foo = true;

DB::collection('something')->raw(function ($collection) use ($foo) {
    echo $foo;// now it works
});