Jit*_*ose 18 php geospatial laravel eloquent laravel-5
如何在eloquent ORM中处理mysql空间数据类型?这包括如何创建迁移,插入空间数据和执行空间查询.如果没有实际的解决方案,是否有任何解决方法?
Emi*_*raz 10
我之前实现的解决方法是在模型上使用以下验证获得纬度和经度字段(请参阅Validator类):
$rules = array('latitude' => 'required|numeric|between:-90,90',
'longitude'=>'required|numeric|between:-180,180',)
Run Code Online (Sandbox Code Playgroud)
魔术来自模型的启动方法,它设置空间点字段的正确值:
/**
* 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);
}
});
}
Run Code Online (Sandbox Code Playgroud)
关于迁移,如@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)' );
Run Code Online (Sandbox Code Playgroud)
小智 6
可以使用https://github.com/grimzy/laravel-mysql-spatial
你可以使用:
namespace App;
use Illuminate\Database\Eloquent\Model;
use Grimzy\LaravelMysqlSpatial\Eloquent\SpatialTrait;
/**
* @property \Grimzy\LaravelMysqlSpatial\Types\Point $location
*/
class Place extends Model
{
use SpatialTrait;
protected $fillable = [
'name',
];
protected $spatialFields = [
'location',
];
}
Run Code Online (Sandbox Code Playgroud)
然后您就可以在“位置”字段上运行查询。
要存储模型,您可以使用:
$place1 = new Place();
$place1->name = 'Empire State Building';
$place1->location = new Point(40.7484404, -73.9878441);
$place1->save();
Run Code Online (Sandbox Code Playgroud)
要检索模型,您应该使用:
$place2 = Place::first();
$lat = $place2->location->getLat(); // 40.7484404
$lng = $place2->location->getLng(); // -73.9878441
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5232 次 |
| 最近记录: |