【发布时间】:2021-02-18 08:33:49
【问题描述】:
我的表中有location 列是POINT 数据类型,我正在尝试检索具有特定经度和纬度的位置,但每次尝试时我都会得到空集合。
迁移:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateBranchesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('branches', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->point('location');
$table->spatialIndex('location');
$table->foreignId('supplier_id')->constrained();
$table->boolean('is_main')->default(false);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('branches');
}
}
型号:
<?php
namespace App\Models;
use App\Casts\PointCasting;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Grimzy\LaravelMysqlSpatial\Eloquent\SpatialTrait;
class Branch extends Model
{
use HasFactory, SpatialTrait;
protected $fillable = [
'location',
'supplier_id',
];
protected $spatialFields = [
'location'
];
protected $casts = [
'location' => PointCasting::class
];
PointCasting.php
<?php
namespace App\Casts;
use Grimzy\LaravelMysqlSpatial\Types\Point;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
class PointCasting implements CastsAttributes
{
/**
* Cast the given value.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $key
* @param mixed $value
* @param array $attributes
* @return mixed
*/
public function get($model, $key, $value, $attributes)
{
return [
'Lat' => $value->getLat(),
'Lng' =>$value->getLng()
];
}
/**
* Prepare the given value for storage.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $key
* @param array $value
* @param array $attributes
* @return mixed
*/
public function set($model, $key, $value, $attributes)
{
return new Point($value['lat'], $value['lon']);
}
}
我试过了:
Branch::where('location', new Grimzy\LaravelMysqlSpatial\Types\Point(50.1, 40.01))->get();
Branch::where('location', new Grimzy\LaravelMysqlSpatial\Types\Point(40.01, 50.1))->get();
Branch::where('location', [50.01, 40.01])->get();
Branch::where('location', [40.01, 50.1])->get();
我使用的包是:grimzy/laravel-mysql-spatial
我试图检索的数据在那里,因为当我尝试使用 phpmyadmin 时,它会出现:
【问题讨论】:
标签: laravel eloquent laravel-8