在Laravel雄辩的ORM中处理Mysql Spatial数据类型 [英] Handling Mysql Spatial datatypes in Laravel Eloquent ORM

查看:238
本文介绍了在Laravel雄辩的ORM中处理Mysql Spatial数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to handle mysql spatial datatypes in eloquent ORM?, This include how to create migration, insert spatial data and performing spatial query's. If there is not actual solutions exists, is there any workarounds?

推荐答案

纬度和经度字段,具有以下验证(请参阅验证器类):

A workaround I have implemented a while ago is to have a latitude and longitude fields on the model with the following validations (see Validator class):

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

魔术来自引导方法,该模型设置空间点字段的正确值:

The magic comes on the boot method of the model, which sets the correct value of the spatial point field:

/**
 * 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 ::语句方法来自定义迁移。

About migrations, like @jhmilan says you can always use the Schema::create and DB::statement methods to customize the migration.

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)' );

这篇关于在Laravel雄辩的ORM中处理Mysql Spatial数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆