我遇到了一个问题,将数据插入数据库中的数据库中。我有这个测试种子功能
$latitude = rand(45.500000 * 1000000, 46.400000 * 1000000) / 1000000;
$longitude = rand(13.600000 * 1000000, 15.500000 * 1000000) / 1000000;
$data = array(
'unique_id' => '12319334',
'latitude' => $latitude,
'longitude' => $longitude,
'coordinates' => "ST_GeomFromText('POINT($latitude $longitude)')",
);
$locationId = $this->Locations->insert($data);
这是模型中的插入函数
function insert($data, $tableName = "")
{
if ($tableName == "") {
$tableName = $this->table;
}
$this->db->insert($tableName, $data);
return $this->db->insert_id();
}
这是发生的查询
INSERT
INTO
`locations`(
`unique_id`,
`latitude`,
`longitude`,
`coordinates`
)
VALUES(
'ZTE1NGY2YT',
45.990292,
14.948462,
'ST_GeomFromText('POINT(45.582315 14.821478)')'
)
错误我得到的是 Cannot get geometry object from data you send to the GEOMETRY field
在phpmyadmin中进行了一些测试后,我发现插入这种数据的查询应该看起来像
INSERT
INTO
`locations`(
`unique_id`,
`latitude`,
`longitude`,
`coordinates`
)
VALUES(
'ZTE1NGY2YT',
45.990292,
14.948462,
ST_GeomFromText('POINT(45.582315 14.821478)')
)
所以我需要以某种方式删除'ST_GeomFromText('POINT(45.582315 14.821478)')'
行中的单语('(
任何人都知道如何正确准备数据(由于没有执行直接查询,因为还有更多数据要存储(,因此可以正确处理?
如果您需要任何其他信息,请告诉我,我将提供。谢谢!
实际上做到了
$this->db->set('coordinates', "ST_GeomFromText('POINT($latitude $longitude)')", false);
所以我对模型进行了一个小的黑客攻击(我知道它不是很漂亮,但现在起作用了(,并且数据插入了。
function insert($data, $tableName = "")
{
foreach ($data as $key => $value) {
if ($key == 'coordinates') {
$this->db->set('coordinates', $value, false);
unset($data['coordinates']);
}
}
if ($tableName == "") {
$tableName = $this->table;
}
$this->db->insert($tableName, $data);
return $this->db->insert_id();
}
不幸的是,CodeIgniter的数据库逃脱逻辑假设该模式为field_name => rendered data
。这意味着您不能使用NOW()
或MD5()
或ST_GeomFromText
之类的东西。您可以在这里看到逻辑:
foreach ($data as $key => $val)
{
$fields[] = $this->escape_identifiers($key);
$values[] = $this->escape($val);
}
我管理的最佳选择是扩展数据库驱动程序并将模型调用为自定义功能。另一个选项是放回原始SQL并手动逃脱值。