Laravel-mongodb insertMany(嵌入关系)未提交

时间:2018-10-22 06:44:14

标签: php mongodb laravel

我想将一个数组插入到对象中,如下图所示,并嵌入到mongodb集合中:

[ 
  [
        "lat"=> 59.56555555455,
        "lon"=> 35.54598994564,
        "type"=> "manual"
  ],...
 ]

enter image description here

为实现这一点,我编写了以下代码。当我使用foreache时确实有效,但是当我想在原始查询日志中使用InsertMany时,它会向我显示插入的对象,但是当我检查数据库时,不会提交任何更改!我的错误在哪里?

日志

InsertManyResult {#302
-writeResult: WriteResult {#301}
-insertedIds: array:3 [
0 => ObjectId {#297
  +"oid": "5bcd6d636925022398005981"
}
1 => ObjectId {#281
  +"oid": "5bcd6d636925022398005982"
}
2 => ObjectId {#298
  +"oid": "5bcd6d636925022398005983"
}
 ]
 -isAcknowledged: true
}```

代码

    $userTraffic = Auth::user()->userTraffic()->firstOrFail();

    if ($userTraffic) {

     $userTraffic->traffics()->raw( function ( $collection ) use ($traffic) {

            $data= $collection->insertMany($traffic);
            dd($data);
            return $data;
        });

        /*  foreach ($traffic as $field) {
              $userTraffic->traffics()->create($field);
          }*/

        return response(['status'=>true,'UserID:'=> Auth::id(),'data'=>$traffic,'insert'=>$userTraffic], 200);
    }
    else return response(['status'=>false,'message'=>'traffic\'s user not found'], 404);



}

- answer:

只需使用$userTraffic->traffics()->createMany($traffic);即可:);

0 个答案:

没有答案