如何使用laravel raw查询和参数插入表中?

时间:2018-07-28 05:53:24

标签: mysql laravel

DB::table('my_table')->insertGetId([
    ...
    'code' => $data['code'],
    'geopoint' => \DB::raw('POINT(?, ?)', [$data['lat'], $data['lng']]),
    ...
]);

它返回

Invalid parameter number (SQL: insert into `residence` (`code`, values (POINT(, ), , ?, ?)

我该如何解决?

谢谢

1 个答案:

答案 0 :(得分:0)

尝试这种方式

为要插入的值创建数组,将与表中的字段名称相同的应用键应用于

$point = DB::select("SELECT POINT($data['lat'], $data['lng']) as point FROM `any_table_name_avilable_in_your_db` LIMIT 1"); 

$data=array(
    "lat_field_name_table"=>$data['lat'],
    "lng_field_name_table"=>$data['lng'],
    "location"=>$point[0]->point
);

$checkinsert=DB::table('mytablename')->insert($data);

然后检查是否按这样插入了数据

if($checkinsert>0){
    //data inserted 
   //do whatever you want if inserted
}else{
   //data not inserted 
   //do whatever you want if not inserted
}

或以这种方式:

$point = DB::select("SELECT POINT($data['lat'], $data['lng']) as point FROM any_table_name_avilable_in_your_db LIMIT 1"); 

DB::table('my_table')->insertGetId([ 
... 
'code' => $data['code'], 
'geopoint' =>$point[0]->point , 
... 
]);