gpt4 book ai didi

php - 在 Laravel Eloquent ORM 中处理 Mysql Spatial 数据类型

转载 作者:IT王子 更新时间:2023-10-29 00:08:35 27 4
gpt4 key购买 nike

如何在 eloquent ORM 中处理 mysql 空间数据类型?,这包括如何创建迁移、插入空间数据和执行空间查询。如果不存在实际的解决方案,是否有任何解决方法?

最佳答案

我刚才实现的一个解决方法是在模型上有一个纬度和经度字段并进行以下验证(参见 Validator class ):

$rules = array('latitude' => 'required|numeric|between:-90,90',
'longitude'=>'required|numeric|between:-180,180',)

魔法降临 boot method模型,它设置了空间点字段的正确值:

/**
* Boot method
* @return void
*/
public static function boot(){
parent::boot();
static::creating(function($eloquentModel){

if(isset($eloquentModel->latitude, $eloquentModel->longitude)){
$point = $eloquentModel->geoToPoint($eloquentModel->latitude, $eloquentModel->longitude);
$eloquentModel->setAttribute('location', DB::raw("GeomFromText('POINT(" . $point . ")')") );
}

});

static::updated(function($eloquentModel){

if(isset($eloquentModel->latitude, $eloquentModel->longitude)){
$point = $eloquentModel->geoToPoint($eloquentModel->latitude, $eloquentModel->longitude);
DB::statement("UPDATE " . $eloquentModel->getTable() . " SET location = GeomFromText('POINT(" . $point . ")') WHERE id = ". $eloquentModel->id);
}

});
}

关于迁移,就像@jhmilan 说的那样,您始终可以使用 Schema::create 和 DB::statement 方法来自定义迁移。

Schema::create('locations', function($table){
$table->engine = "MYISAM";
$table->increments('id')->unsigned();
$table->decimal('latitude', 10, 8);
$table->decimal('longitude', 11, 8);
$table->timestamps();
});

/*Espatial Column*/
DB::statement('ALTER TABLE locations ADD location POINT NOT NULL' );
/*Espatial index (MYISAM only)*/
DB::statement( 'ALTER TABLE locations ADD SPATIAL INDEX index_point(location)' );

关于php - 在 Laravel Eloquent ORM 中处理 Mysql Spatial 数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30682538/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com