如何解决Symfony 5异常:Unknown database type point requested, Doctrine\DBAL\Platforms\MySQL57Platform may not support it

2021年11月29日19:51:21 发表评论 803 次浏览

了解如何轻松地让 Doctrine 从空间数据类型自动生成实体。

如何解决Symfony 5异常:Unknown database type point requested, Doctrine\DBAL\Platforms\MySQL57Platform may not support it

最近,在我目前正在进行的一个新项目中,我一直在使用一种我从未在生产项目中使用过的新数据类型,即Point数据类型。在本例中,我使用 MySQL 作为数据库引擎,因此插入和修改使用上述数据类型的记录非常简单:

INSERT INTO `tableName`
    (`id`, `name`, `coordinates`) 
        VALUES 
    (NULL, 'My First Record', ST_GeomFromText('POINT(40.71727401 -74.00898606)'));

但是,我将 Doctrine ORM 与 Symfony 5 一起使用,因此在使其完美运行之前需要进行一些调整。在使用这种数据类型时,你在 Symfony 中可能面临的问题之一是,它不能被doctrine:mapping:import命令自动映射以进行逆向工程。这意味着,如果你有一个已经存在的数据库,并且你尝试使用以下命令自动生成实体:

php bin/console doctrine:mapping:import "App\Entity" "annotation" --path=src/Entity

如何修复错误Unknown database type point requested?将出现指定的异常(请求的数据库类型未知)。幸运的是,Doctrine 确实支持它,但是你需要安装 Doctrine 2 Spatial 扩展才能使其工作。在这个简短的教程中,我将向你解释如何轻松地允许对具有空间数据类型的数据库进行逆向工程。

1. 安装 Doctrine 2 Spatial Extension

Unknown database type point requested解决办法:要解决此问题,你需要安装 Doctrine 2 Spatial Extension。这个 Doctrine2 库为空间类型和函数提供多平台支持。目前,支持带有 PostGIS 的 MySQL 和 PostgreSQL。以下 SQL/OpenGIS 类型已作为 PHP 对象和随附的 Doctrine 类型实现:

  • Geometry
  • Point
  • LineString
  • Polygon
  • MultiPoint
  • MultiLineString
  • MultiPolygon
  • Geography

与 Geometry 类似,但始终使用 SRID 值(仅 PostGIS 支持 SRID),并且仅接受有效的“地理”坐标。

  • Point
  • LineString
  • Polygon

支持 WKB/WKT 和 EWKB/EWKT 返回值。目前在语句中仅使用 WKT/EWKT。要安装此扩展,请在你的 Symfony 项目中运行以下命令:

composer require creof/doctrine2-spatial

有关此项目的更多信息,请在此处访问 Github 的官方存储库

2. 启用Point类型

Unknown database type point requested解决办法:安装扩展库后,只需启用需要添加映射支持的类型即可。在这种情况下,我只需要Point数据类型,因此以下配置将对doctrine.yaml配置文件起作用:

# project/config/packages/doctrine.yaml
doctrine:
    dbal:
        url: '%env(resolve:DATABASE_URL)%'
        types:
            point: CrEOF\Spatial\DBAL\Types\Geometry\PointType

如何修复错误Unknown database type point requested?相同的过程适用于不同的类型,如Geometry, MultiPoint, MultiPolygon, Polygon, LineString, MultineString。请务必清除 symfony 项目的缓存并再次尝试映射。你自动生成的实体现在将包含Point类型的列:

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * ExampleEntity
 *
 * @ORM\Table(name="example", indexes={@ORM\Index(name="coordinates", columns={"coordinates"})})
 * @ORM\Entity
 */
class Example
{
    /**
     * @var point
     *
     * @ORM\Column(name="coordinates", type="point", nullable=true)
     */
    private $coordinates;

    public function getCoordinates()
    {
        return $this->coordenadas;
    }

    public function setCoordinates($coordinates): self
    {
        $this->coordinates = $coordinates;

        return $this;
    }
}

快乐编码❤️!

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: