doctrine 是 symfony 默认 orm,通过“配置→实体→迁移→操作”四步实现数据库操作:先配置连接与自动映射,再用 make:entity 创建带注解的实体,生成并执行迁移建表,最后通过 entitymanager 执行 crud 并封装查询至 repository。

Doctrine 是 Symfony 默认集成的 ORM 工具,用它操作数据库不靠写 SQL,而是通过 PHP 类(实体)和对象方法完成增删改查。核心在于“配置 → 实体 → 迁移 → 操作”四步闭环,跳过任一环都可能报错或数据不同步。
配置数据库连接与基础参数
先确保 Doctrine Bundle 和 ORM 组件已安装:
- 运行 composer require doctrine/doctrine-bundle doctrine/orm
- 在 .env 中设置连接串,例如:
DATABASE_URL="mysql://root:pass@127.0.0.1:3306/myapp?serverVersion=8.0" - 检查 config/packages/doctrine.yaml 是否启用 ORM 并开启自动映射:
doctrine: orm: auto_mapping: true
创建实体类并生成数据库表
实体是 PHP 类,它既是业务模型,也定义了数据库结构:
- 执行 php bin/console make:entity Product,按提示输入字段名(如 name)、类型(如 string)、长度(如 255)
- 命令自动生成 src/Entity/Product.php,含注解(如
@ORM\Column(type="string")) - 生成迁移文件:php bin/console make:migration
- 执行迁移建表:php bin/console doctrine:migrations:migrate
用 EntityManager 执行基本 CRUD
所有数据操作都经由 EntityManagerInterface,不能直连 PDO:
- 控制器中注入:
public function index(EntityManagerInterface $em) - 新增:
$product = new Product();
$product->setName('Book');
$em->persist($product);
$em->flush(); - 查询:
$product = $em->getRepository(Product::class)->find(1); - 更新或删除后,必须调用 $em->flush() 才真正生效
封装查询逻辑到 Repository
避免在控制器里写复杂查询,把逻辑移到 Repository 中更清晰、易测试:
- 运行 php bin/console make:repository ProductRepository
- 在 ProductRepository.php 中添加方法,例如:
public function findByName(string $name): ?Product
{ return $this->findOneBy(['name' => $name]); } - 控制器中调用:
$product = $this->getDoctrine()->getRepository(Product::class)->findByName('Book');











