当我在原始函数中调用$id
和$tid
来从mongodb集合的子文档中获取某些数据时,它会显示错误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;
}
?>
答案 0 :(得分:1)
当你在PHP中使用回调函数时,函数就像它拥有的范围一样,并且不能从它的范围之外访问变量。
$foo = true;
DB::collection('something')->raw(function ($collection) {
echo $foo;// $foo is undefined here, this create an error
});
echo $foo;// here it work
但您可以使用PHP use
keyword:
$foo = true;
DB::collection('something')->raw(function ($collection) use ($foo) {
echo $foo;// now it works
});
答案 1 :(得分:0)
它可以很好地添加批量,这样你只需要在数组上创建并传递它。
$temp = [
[
'item' => "envelopes"
],
[
'item' => "envelopesas"
],
[
'item' => "lala"
]
];
$userData = DB::table('log') - > raw(function ($collection) use($temp)
{
return $collection - > insertMany($temp);
});