如何在 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/

10-09 08:26
查看更多