如何通过 Symfony 4 连接到使用 MAMP 创建的 mySQL 数据库?

How can I connect via Symfony 4 to mySQL database created with MAMP?

我在 MAMP 中创建了一个名为 "project" 的数据库。

在我的 .env 文件中,我添加了这一行:

DATABASE_URL=mysql://root:root@localhost:3306/project

现在我想运行

php bin/console doctrine:database:create

但我收到一条错误消息:

SQLSTATE[HY000] [2002] No such file or directory

我的学说配置:

parameters:
    # Adds a fallback DATABASE_URL if the env var is not set.
    # This allows you to run cache:warmup even if your
    # environment variables are not available yet.
    # You should not need to change this value.
    env(DATABASE_URL): ''

doctrine:
    dbal:
        # configure these for your database server
        driver: 'pdo_mysql'
        server_version: '5.7'
        charset: utf8mb4
        default_table_options:
            charset: utf8mb4
            collate: utf8mb4_unicode_ci

        url: '%env(resolve:DATABASE_URL)%'
    orm:
        auto_generate_proxy_classes: '%kernel.debug%'
        naming_strategy: doctrine.orm.naming_strategy.underscore
        auto_mapping: true
        mappings:
            App:
                is_bundle: false
                type: annotation
                dir: '%kernel.project_dir%/src/Entity'
                prefix: 'App\Entity'
                alias: App

尝试改变这个:

url: '%env(resolve:DATABASE_URL)%'

对此:

url: '%env(DATABASE_URL)%'

解决了!

在文件中 "config/packages/doctrine.yaml" 我不得不添加这一行

unix_socket: /Applications/MAMP/tmp/mysql/mysql.sock

这意味着改变这个:

 dbal:
        # configure these for your database server
        driver: 'pdo_mysql'
        server_version: '5.7'
        charset: utf8mb4
        default_table_options:
            charset: utf8mb4
            collate: utf8mb4_unicode_ci

        url: '%env(resolve:DATABASE_URL)%'

进入

 dbal:
        # configure these for your database server
        driver: 'pdo_mysql'
        server_version: '5.7'
        charset: utf8mb4
        unix_socket: /Applications/MAMP/tmp/mysql/mysql.sock
        default_table_options:
            charset: utf8mb4
            collate: utf8mb4_unicode_ci

        url: '%env(resolve:DATABASE_URL)%'

您还可以尝试显式设置 mysql 服务器

doctrine:
    dbal:
        default_connection: default
        connections:
            default:
                dbname:         local_api
                user:           root
                password:       null
                host:           localhost
                driver:         pdo_mysql
                server_version: '5.5' # in case you are using mysql 5.5

遇到了同样的问题。添加了 unix_socket 并将 127.0.0.1 更改为 localhost 适用于 MAMP 5.5。

doctrine.yaml

doctrine:
dbal:
    # configure these for your database server
    driver: 'pdo_mysql'
    server_version: '5.7'
    charset: utf8mb4
    unix_socket: /Applications/MAMP/tmp/mysql/mysql.sock
    default_table_options:
        charset: utf8mb4
        collate: utf8mb4_unicode_ci

    url: '%env(resolve:DATABASE_URL)%'

.env

DATABASE_URL=mysql://root:root@localhost:3306/mydb