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

ⅰ亾dé卋堺 提交于 2019-12-11 08:20:26

问题


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
});


来源:https://stackoverflow.com/questions/28576524/how-to-pass-variables-tid-id-into-raw-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!