You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Laravel 8中向PostGIS数据库插入地理点?

在Laravel中向PostGIS的geography列插入经纬度数据

方法一:使用DB门面直接执行插入

PostGIS提供ST_MakePoint函数生成点几何对象,结合ST_SetSRID指定坐标系(通常用WGS84的4326),再转换为geography类型即可。

注意:PostGIS中经度在前,纬度在后,别搞反顺序。

基础写法(需注意SQL注入风险)

$longitude = 116.3972;
$latitude = 39.9075;

DB::table('your_table')->insert([
    'geo_column' => DB::raw("ST_SetSRID(ST_MakePoint($longitude, $latitude), 4326)::geography"),
    // 其他需要插入的字段
]);

安全写法(参数绑定防注入)

$longitude = 116.3972;
$latitude = 39.9075;

DB::table('your_table')->insert(
    [
        'geo_column' => DB::raw("ST_SetSRID(ST_MakePoint(?, ?), 4326)::geography"),
        // 其他字段
    ],
    [$longitude, $latitude]
);

方法二:使用Eloquent模型处理

通过模型的**修改器(Mutator)**封装坐标处理逻辑,让代码更简洁可复用。

1. 在模型中定义修改器

class Location extends Model
{
    protected $fillable = ['geo_column', 'name']; // 按需添加允许批量赋值的字段

    /**
     * 处理geography列的赋值
     * @param array $value 包含lat(纬度)和lng(经度)的数组
     */
    public function setGeoColumnAttribute($value)
    {
        if (is_array($value) && isset($value['lat'], $value['lng'])) {
            $this->attributes['geo_column'] = DB::raw("ST_SetSRID(ST_MakePoint({$value['lng']}, {$value['lat']}), 4326)::geography");
        }
    }
}

2. 使用模型插入数据

$longitude = 116.3972;
$latitude = 39.9075;

Location::create([
    'geo_column' => ['lat' => $latitude, 'lng' => $longitude],
    'name' => '北京天安门' // 示例其他字段
]);

关键注意事项

  • 确认你的geography字段使用的坐标系SRID,示例中用的4326是全球通用的GPS坐标系,若你的字段是其他SRID,需同步修改ST_SetSRID的第二个参数。
  • 始终优先使用参数绑定或Eloquent的方式,避免直接拼接变量到SQL语句中,防止SQL注入。

内容的提问来源于stack exchange,提问作者Čamo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 08:47:30