当前位置:首页>php>Php Doctrine ORM 实战详解:从实体映射到查询、关联与事务

Php Doctrine ORM 实战详解:从实体映射到查询、关联与事务

  • 2026-06-28 03:22:49
Php Doctrine ORM 实战详解:从实体映射到查询、关联与事务

简介

Doctrine ORM 是 PHP 生态里非常常见的对象关系映射框架,Symfony 项目中用得尤其多。

它的作用可以用一句话概括:

把数据库表映射成 PHP 对象,通过操作对象完成增删改查,最后由 Doctrine 生成并执行 SQL。

传统写法通常是直接写 SQL:

$stmt = $pdo->prepare('INSERT INTO product (name, price) VALUES (?, ?)');$stmt->execute(['机械键盘', 39900]);

使用 Doctrine 后,代码会变成操作实体对象:

$product = new Product();$product->setName('机械键盘');$product->setPrice(39900);$em->persist($product);$em->flush();

表面上只是写法变了,底层做的事情更多:

  • • Product 类映射到 product 表
  • • $product->setName() 修改对象属性
  • • persist() 把新对象交给 Doctrine 管理
  • • flush() 统一生成并执行 SQL
  • • 修改已有对象时,Doctrine 会做变更追踪

Doctrine 适合实体结构比较清晰、业务围绕对象展开、需要迁移、关联查询、事务管理的 PHP 项目。

Doctrine、DBAL、ORM 的关系

Doctrine 不是只有 ORM。

常见几个概念如下:

名称
作用
Doctrine DBAL
数据库抽象层,封装连接、SQL 执行、参数绑定、不同数据库差异
Doctrine ORM
对象关系映射,把 PHP 类和数据库表关联起来
Doctrine Migrations
数据库迁移工具,根据实体变化生成表结构变更
Doctrine Bundle
Symfony 集成包,把 Doctrine 接入 Symfony 配置、容器和命令行

在 Symfony 项目中,常见调用链大致是:

Controller  |  vService  |  vRepository  |  vEntityManager  |  vDoctrine ORM  |  vDoctrine DBAL  |  vMySQL / PostgreSQL / SQLite

其中最核心的对象是 EntityManager

它负责管理实体对象的生命周期,包括新增、修改、删除、查询、事务提交等。

安装 Doctrine

Symfony 项目中一般直接安装 orm-pack

composer require symfony/orm-pack

开发环境常用代码生成器:

composer require --dev symfony/maker-bundle

如果需要查看 SQL、请求耗时、数据库查询次数,可以安装 Profiler:

composer require --dev symfony/profiler-pack

安装完成后,可以查看 Doctrine 相关包:

composer show doctrine/*

配置数据库连接

.env 中配置 DATABASE_URL

MySQL 示例:

DATABASE_URL="mysql://root:123456@127.0.0.1:3306/doctrine_demo?serverVersion=8.0&charset=utf8mb4"

PostgreSQL 示例:

DATABASE_URL="postgresql://app:123456@127.0.0.1:5432/doctrine_demo?serverVersion=16&charset=utf8"

常见格式:

数据库类型://用户名:密码@主机:端口/数据库名?参数

创建数据库:

php bin/console doctrine:database:create

如果数据库已经存在,这一步可以跳过。

准备一个商品订单 Demo

下面用一个小型商品订单场景演示 Doctrine。

实体关系如下:

Category 1 ---- N ProductProduct  1 ---- N OrderItemOrder    1 ---- N OrderItem

也就是:

  • • 一个分类下有多个商品
  • • 一个订单有多条订单明细
  • • 一条订单明细对应一个商品

这比单表 CRUD 更接近真实项目,也能把关联关系、查询、事务串起来。

创建 Category 实体

可以使用命令生成:

php bin/console make:entity Category

字段示例:

name string 100 not null

实体代码可以写成下面这样:

<?phpnamespace App\Entity;use App\Repository\CategoryRepository;use Doctrine\Common\Collections\ArrayCollection;use Doctrine\Common\Collections\Collection;use Doctrine\ORM\Mapping as ORM;#[ORM\Entity(repositoryClass: CategoryRepository::class)]class Category{    #[ORM\Id]    #[ORM\GeneratedValue]    #[ORM\Column]    private ?int $id = null;    #[ORM\Column(length: 100)]    private ?string $name = null;    /**     * @var Collection<int, Product>     */    #[ORM\OneToMany(mappedBy: 'category', targetEntity: Product::class)]    private Collection $products;    publicfunction __construct(){        $this->products = new ArrayCollection();    }    publicfunction getId(): ?int{        return $this->id;    }    publicfunction getName(): ?string{        return $this->name;    }    publicfunction setName(string $name): static{        $this->name = $name;        return $this;    }    /**     * @return Collection<int, Product>     */    publicfunction getProducts(): Collection{        return $this->products;    }}

这里有几个重点:

  • • #[ORM\Entity] 表示这个类是实体
  • • #[ORM\Id] 表示主键
  • • #[ORM\GeneratedValue] 表示主键由数据库生成
  • • #[ORM\Column] 表示普通字段
  • • #[ORM\OneToMany] 表示一对多关系

products 不是数据库中的普通字段,而是关联对象集合。

创建 Product 实体

商品实体包含名称、价格、库存、创建时间、所属分类。

价格建议用整数保存,单位为分,避免浮点数精度问题。

<?phpnamespace App\Entity;use App\Repository\ProductRepository;use Doctrine\Common\Collections\ArrayCollection;use Doctrine\Common\Collections\Collection;use Doctrine\DBAL\Types\Types;use Doctrine\ORM\Mapping as ORM;#[ORM\Entity(repositoryClass: ProductRepository::class)]#[ORM\Table(name: 'product')]class Product{    #[ORM\Id]    #[ORM\GeneratedValue]    #[ORM\Column]    private ?int $id = null;    #[ORM\Column(length: 150)]    private ?string $name = null;    #[ORM\Column]    private int $price = 0;    #[ORM\Column]    private int $stock = 0;    #[ORM\Column(type: Types::TEXT, nullable: true)]    private ?string $description = null;    #[ORM\Column]    private \DateTimeImmutable $createdAt;    #[ORM\ManyToOne(inversedBy: 'products')]    #[ORM\JoinColumn(nullable: false)]    private ?Category $category = null;    /**     * @var Collection<int, OrderItem>     */    #[ORM\OneToMany(mappedBy: 'product', targetEntity: OrderItem::class)]    private Collection $orderItems;    publicfunction __construct(){        $this->createdAt = new \DateTimeImmutable();        $this->orderItems = new ArrayCollection();    }    publicfunction getId(): ?int{        return $this->id;    }    publicfunction getName(): ?string{        return $this->name;    }    publicfunction setName(string $name): static{        $this->name = $name;        return $this;    }    publicfunction getPrice(): int{        return $this->price;    }    publicfunction setPrice(int $price): static{        $this->price = $price;        return $this;    }    publicfunction getStock(): int{        return $this->stock;    }    publicfunction setStock(int $stock): static{        $this->stock = $stock;        return $this;    }    publicfunction getDescription(): ?string{        return $this->description;    }    publicfunction setDescription(?string $description): static{        $this->description = $description;        return $this;    }    publicfunction getCreatedAt(): \DateTimeImmutable{        return $this->createdAt;    }    publicfunction getCategory(): ?Category{        return $this->category;    }    publicfunction setCategory(?Category $category): static{        $this->category = $category;        return $this;    }}

ManyToOne 是业务开发中最常见的关系。

#[ORM\ManyToOne(inversedBy: 'products')]#[ORM\JoinColumn(nullable: false)]private ?Category $category = null;

这段代码表示:

多个商品属于同一个分类,product 表中会有 category_id 外键。

创建 Order 和 OrderItem 实体

订单实体:

<?phpnamespace App\Entity;use App\Repository\OrderRepository;use Doctrine\Common\Collections\ArrayCollection;use Doctrine\Common\Collections\Collection;use Doctrine\ORM\Mapping as ORM;#[ORM\Entity(repositoryClass: OrderRepository::class)]#[ORM\Table(name: '`order`')]class Order{    #[ORM\Id]    #[ORM\GeneratedValue]    #[ORM\Column]    private ?int $id = null;    #[ORM\Column(length: 50)]    private string $orderNo;    #[ORM\Column]    private int $totalAmount = 0;    #[ORM\Column(length: 20)]    private string $status = 'pending';    #[ORM\Column]    private \DateTimeImmutable $createdAt;    /**     * @var Collection<int, OrderItem>     */    #[ORM\OneToMany(mappedBy: 'order', targetEntity: OrderItem::class, cascade: ['persist'], orphanRemoval: true)]    private Collection $items;    publicfunction __construct(){        $this->orderNo = date('YmdHis') . random_int(1000, 9999);        $this->createdAt = new \DateTimeImmutable();        $this->items = new ArrayCollection();    }    publicfunction getId(): ?int{        return $this->id;    }    publicfunction getOrderNo(): string{        return $this->orderNo;    }    publicfunction getTotalAmount(): int{        return $this->totalAmount;    }    publicfunction setTotalAmount(int $totalAmount): static{        $this->totalAmount = $totalAmount;        return $this;    }    publicfunction getStatus(): string{        return $this->status;    }    publicfunction setStatus(string $status): static{        $this->status = $status;        return $this;    }    /**     * @return Collection<int, OrderItem>     */    publicfunction getItems(): Collection{        return $this->items;    }    publicfunction addItem(OrderItem $item): static{        if (!$this->items->contains($item)) {            $this->items->add($item);            $item->setOrder($this);        }        return $this;    }}

订单明细实体:

<?phpnamespace App\Entity;use App\Repository\OrderItemRepository;use Doctrine\ORM\Mapping as ORM;#[ORM\Entity(repositoryClass: OrderItemRepository::class)]class OrderItem{    #[ORM\Id]    #[ORM\GeneratedValue]    #[ORM\Column]    private ?int $id = null;    #[ORM\ManyToOne(inversedBy: 'items')]    #[ORM\JoinColumn(nullable: false)]    private ?Order $order = null;    #[ORM\ManyToOne(inversedBy: 'orderItems')]    #[ORM\JoinColumn(nullable: false)]    private ?Product $product = null;    #[ORM\Column]    private int $quantity = 1;    #[ORM\Column]    private int $unitPrice = 0;    publicfunction getId(): ?int{        return $this->id;    }    publicfunction getOrder(): ?Order{        return $this->order;    }    publicfunction setOrder(?Order $order): static{        $this->order = $order;        return $this;    }    publicfunction getProduct(): ?Product{        return $this->product;    }    publicfunction setProduct(?Product $product): static{        $this->product = $product;        return $this;    }    publicfunction getQuantity(): int{        return $this->quantity;    }    publicfunction setQuantity(int $quantity): static{        $this->quantity = $quantity;        return $this;    }    publicfunction getUnitPrice(): int{        return $this->unitPrice;    }    publicfunction setUnitPrice(int $unitPrice): static{        $this->unitPrice = $unitPrice;        return $this;    }    publicfunction getAmount(): int{        return $this->unitPrice * $this->quantity;    }}

Order 表名使用了反引号:

#[ORM\Table(name: '`order`')]

原因是 order 在 SQL 中经常和排序关键字 ORDER BY 撞名。实际项目中也可以直接使用 orders 作为表名。

生成迁移并创建表

实体写好后,需要生成迁移文件:

php bin/console make:migration

执行迁移:

php bin/console doctrine:migrations:migrate

迁移文件通常位于:

migrations/Versionxxxxxxxxxxxx.php

迁移文件记录表结构变化,例如创建表、添加字段、创建索引、添加外键等。

常用迁移命令:

查看迁移状态php bin/console doctrine:migrations:status执行迁移php bin/console doctrine:migrations:migrate回滚到上一个版本,版本号按实际情况填写php bin/console doctrine:migrations:migrate prev生成 SQL,不直接执行php bin/console doctrine:migrations:migrate --dry-run

实体类只是 PHP 代码,数据库不会自动多出表。迁移执行成功后,表结构才会真正落到数据库中。

新增数据:persist 和 flush

创建一个控制器用于添加分类和商品:

<?phpnamespace App\Controller;use App\Entity\Category;use App\Entity\Product;use Doctrine\ORM\EntityManagerInterface;use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;use Symfony\Component\HttpFoundation\Response;use Symfony\Component\Routing\Attribute\Route;class ProductDemoController extends AbstractController{    #[Route('/demo/products/seed', name: 'demo_products_seed')]    publicfunction seed(EntityManagerInterface $em): Response{        $category = new Category();        $category->setName('数码配件');        $keyboard = new Product();        $keyboard->setName('机械键盘')            ->setPrice(39900)            ->setStock(100)            ->setDescription('青轴、有线、白色')            ->setCategory($category);        $mouse = new Product();        $mouse->setName('无线鼠标')            ->setPrice(12900)            ->setStock(200)            ->setDescription('蓝牙双模')            ->setCategory($category);        $em->persist($category);        $em->persist($keyboard);        $em->persist($mouse);        $em->flush();        return new Response('初始化完成');    }}

persist() 和 flush() 很容易混在一起。

简单理解:

persist():把对象放进 Doctrine 管理队列flush():统一计算变化并执行 SQL

上面代码执行时,大致会生成:

INSERT INTO category (name) VALUES ('数码配件');INSERT INTO product (name, price, stock, description, created_at, category_id)VALUES ('机械键盘', 39900, 100, '青轴、有线、白色', '...', 1);INSERT INTO product (name, price, stock, description, created_at, category_id)VALUES ('无线鼠标', 12900, 200, '蓝牙双模', '...', 1);

flush() 之后,数据库生成的主键会回填到实体对象:

$id = $keyboard->getId();

查询数据:Repository 基础方法

Doctrine 会为实体提供 Repository。

常见方法如下:

$repo = $em->getRepository(Product::class);// 按主键查询$product = $repo->find(1);// 查询单条$product = $repo->findOneBy(['name' => '机械键盘']);// 按条件查询多条$products = $repo->findBy(    ['category' => $category],    ['id' => 'DESC'],    10,    0);// 查询全部$products = $repo->findAll();

也可以直接注入 ProductRepository

use App\Repository\ProductRepository;use Symfony\Component\HttpFoundation\JsonResponse;use Symfony\Component\Routing\Attribute\Route;#[Route('/demo/products', name: 'demo_products')]publicfunction list(ProductRepository $repository): JsonResponse{    $products = $repository->findBy([], ['id' => 'DESC'], 20);    $data = array_map(static function (Product $product): array {        return [            'id' => $product->getId(),            'name' => $product->getName(),            'price' => $product->getPrice(),            'stock' => $product->getStock(),            'category' => $product->getCategory()?->getName(),        ];    }, $products);    return new JsonResponse($data);}

findBy() 适合简单等值查询。

比如:

$repository->findBy(['status' => 'pending']);

复杂条件,例如大于、小于、模糊查询、聚合统计、连表查询,更适合使用 QueryBuilder

修改数据:脏检查

Doctrine 管理的对象发生属性变化后,不需要再次 persist()

#[Route('/demo/products/{id}/change-price', name: 'demo_products_change_price')]publicfunction changePrice(    int $id,    ProductRepository $repository,    EntityManagerInterface $em): Response{    $product = $repository->find($id);    if ($product === null) {        return new Response('商品不存在', 404);    }    $product->setPrice(35900);    $em->flush();    return new Response('价格修改完成');}

这就是 Doctrine 的变更追踪,也叫脏检查。

执行流程大致如下:

1. 从数据库查出 Product2. Product 进入 EntityManager 管理状态3. setPrice() 修改对象属性4. flush() 对比原始值和当前值5. 发现 price 变化,生成 UPDATE

类似 SQL:

UPDATE product SET price = 35900 WHERE id = 1;

删除数据:remove 和 flush

删除商品:

#[Route('/demo/products/{id}/delete', name: 'demo_products_delete')]publicfunction delete(    int $id,    ProductRepository $repository,    EntityManagerInterface $em): Response{    $product = $repository->find($id);    if ($product === null) {        return new Response('商品不存在', 404);    }    $em->remove($product);    $em->flush();    return new Response('删除完成');}

remove() 只是标记删除,真正执行 SQL 仍然发生在 flush()

QueryBuilder:复杂查询更常用

在 src/Repository/ProductRepository.php 中添加自定义查询:

<?phpnamespace App\Repository;use App\Entity\Product;use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;use Doctrine\Persistence\ManagerRegistry;/** * @extends ServiceEntityRepository<Product> */class ProductRepository extends ServiceEntityRepository{    publicfunction __construct(ManagerRegistry $registry){        parent::__construct($registry, Product::class);    }    /**     * @return Product[]     */    publicfunction searchAvailableProducts(?string $keyword, int $minPrice, int $maxPrice): array{        $qb = $this->createQueryBuilder('p')            ->innerJoin('p.category', 'c')            ->addSelect('c')            ->andWhere('p.stock > 0')            ->andWhere('p.price BETWEEN :minPrice AND :maxPrice')            ->setParameter('minPrice', $minPrice)            ->setParameter('maxPrice', $maxPrice)            ->orderBy('p.id', 'DESC')            ->setMaxResults(20);        if ($keyword !== null && $keyword !== '') {            $qb->andWhere('p.name LIKE :keyword')                ->setParameter('keyword', '%' . $keyword . '%');        }        return $qb->getQuery()->getResult();    }}

调用:

#[Route('/demo/products/search', name: 'demo_products_search')]publicfunction search(ProductRepository $repository): JsonResponse{    $products = $repository->searchAvailableProducts('键盘', 10000, 50000);    return new JsonResponse(array_map(static function (Product $product): array {        return [            'id' => $product->getId(),            'name' => $product->getName(),            'price' => $product->getPrice(),            'category' => $product->getCategory()?->getName(),        ];    }, $products));}

QueryBuilder 最常见的几个方法:

方法
作用
createQueryBuilder('p')
创建查询构造器,p 是实体别名
andWhere()
添加查询条件
setParameter()
绑定参数
innerJoin()
内连接
leftJoin()
左连接
addSelect()
额外查询关联对象
orderBy()
排序
setMaxResults()
限制数量
setFirstResult()
设置偏移量
getResult()
返回多条实体
getOneOrNullResult()
返回一条或 null

setParameter() 很重要,它会使用参数绑定,避免字符串拼接带来的 SQL 注入风险。

DQL:面向对象的查询语言

Doctrine 还有一种查询方式叫 DQL

它看起来像 SQL,但查询对象是实体类和实体属性,不是表名和字段名。

publicfunction findLowStockProducts(int $stock): array{    return $this->getEntityManager()        ->createQuery(            'SELECT p FROM App\Entity\Product p WHERE p.stock < :stock ORDER BY p.id DESC'        )        ->setParameter('stock', $stock)        ->getResult();}

注意这里写的是:

App\Entity\Productp.stock

不是:

productp.stock_column

DQL 适合表达稳定的复杂查询。动态条件很多时,QueryBuilder 通常更顺手。

分页查询

普通分页可以这样写:

publicfunction findPage(int $page, int $pageSize): array{    $page = max(1, $page);    $offset = ($page - 1) * $pageSize;    return $this->createQueryBuilder('p')        ->orderBy('p.id', 'DESC')        ->setFirstResult($offset)        ->setMaxResults($pageSize)        ->getQuery()        ->getResult();}

同时查询总数:

publicfunction countAll(): int{    return (int) $this->createQueryBuilder('p')        ->select('COUNT(p.id)')        ->getQuery()        ->getSingleScalarResult();}

列表页常见返回结构:

return new JsonResponse([    'items' => $items,    'page' => $page,    'pageSize' => $pageSize,    'total' => $total,]);

数据量很大时,深分页会越来越慢。比如 OFFSET 100000 LIMIT 20,数据库需要先跳过大量记录。

这类场景可以用基于游标的分页:

publicfunction findNextPage(?int $lastId, int $pageSize): array{    $qb = $this->createQueryBuilder('p')        ->orderBy('p.id', 'DESC')        ->setMaxResults($pageSize);    if ($lastId !== null) {        $qb->andWhere('p.id < :lastId')            ->setParameter('lastId', $lastId);    }    return $qb->getQuery()->getResult();}

这种方式适合信息流、后台滚动加载、导出数据等场景。

关联加载:懒加载和主动加载

Doctrine 的关联默认通常是懒加载。

例如:

$product = $productRepository->find(1);$categoryName = $product->getCategory()->getName();

第一行只查商品。

访问 getCategory() 时,Doctrine 才查询分类。

如果列表里有 20 个商品,每个商品再访问一次分类,可能变成:

1 次查询商品列表20 次查询分类

这就是常见的 N + 1 查询问题。

可以通过 join + addSelect 提前加载关联对象:

publicfunction findLatestWithCategory(): array{    return $this->createQueryBuilder('p')        ->innerJoin('p.category', 'c')        ->addSelect('c')        ->orderBy('p.id', 'DESC')        ->setMaxResults(20)        ->getQuery()        ->getResult();}

这样商品和分类会在一条查询里取出来,后续访问分类时不用再额外查一次。

创建订单:事务实战

下单需要同时做几件事:

  • • 查询商品
  • • 判断库存
  • • 扣减库存
  • • 创建订单
  • • 创建订单明细
  • • 保存总金额

这些操作要么全部成功,要么全部失败,所以需要事务。

可以在 Service 中封装下单逻辑:

<?phpnamespace App\Service;use App\Entity\Order;use App\Entity\OrderItem;use App\Repository\ProductRepository;use Doctrine\ORM\EntityManagerInterface;class OrderService{    publicfunction __construct(        private readonly EntityManagerInterface $em,        private readonly ProductRepository $productRepository,{    }    /**     * @param array<int, array{productId: int, quantity: int}> $items     */    publicfunction createOrder(array $items): Order{        return $this->em->wrapInTransaction(function () use ($items): Order {            $order = new Order();            $totalAmount = 0;            foreach ($items as $itemData) {                $product = $this->productRepository->find($itemData['productId']);                if ($product === null) {                    throw new \RuntimeException('商品不存在');                }                $quantity = $itemData['quantity'];                if ($product->getStock() < $quantity) {                    throw new \RuntimeException('商品库存不足');                }                $product->setStock($product->getStock() - $quantity);                $orderItem = new OrderItem();                $orderItem->setProduct($product);                $orderItem->setQuantity($quantity);                $orderItem->setUnitPrice($product->getPrice());                $order->addItem($orderItem);                $totalAmount += $orderItem->getAmount();            }            $order->setTotalAmount($totalAmount);            $this->em->persist($order);            return $order;        });    }}

控制器调用:

use App\Service\OrderService;use Symfony\Component\HttpFoundation\JsonResponse;use Symfony\Component\Routing\Attribute\Route;#[Route('/demo/orders/create', name: 'demo_orders_create')]publicfunction createOrder(OrderService $orderService): JsonResponse{    $order = $orderService->createOrder([        ['productId' => 1, 'quantity' => 2],        ['productId' => 2, 'quantity' => 1],    ]);    return new JsonResponse([        'id' => $order->getId(),        'orderNo' => $order->getOrderNo(),        'totalAmount' => $order->getTotalAmount(),    ]);}

wrapInTransaction() 会自动开启事务。

闭包正常结束时提交事务;闭包抛出异常时回滚事务。

这段代码还有一个细节:

#[ORM\OneToMany(mappedBy: 'order', targetEntity: OrderItem::class, cascade: ['persist'], orphanRemoval: true)]private Collection $items;

cascade: ['persist'] 表示保存 Order 时,关联的 OrderItem 也会一起保存。

所以 Service 中只需要:

$this->em->persist($order);

不需要对每个 OrderItem 单独 persist()

flush 的执行时机

Doctrine 不会每调用一次 setter 就执行一次 SQL。

它会先记录对象状态变化,等到 flush() 时统一处理。

例如:

$product->setName('新名称');$product->setPrice(29900);$product->setStock(50);$em->flush();

通常只会生成一次 UPDATE

这也是 Doctrine 的工作单元模式,也叫 Unit of Work

简单理解:

EntityManager 像一个临时记账本。persist、remove、setter 都是在记账。flush 才是结账。

detach、clear 和实体状态

Doctrine 管理的实体有几种常见状态:

状态
含义
new
新创建的对象,还没有交给 EntityManager
managed
已经被 EntityManager 管理
removed
已标记删除
detached
曾经被管理,后来脱离了 EntityManager

示例:

$product = new Product();$product->setName('显示器');$em->persist($product); // 进入 managed$em->flush();           // 写入数据库$em->detach($product);  // 脱离管理$product->setName('曲面显示器');$em->flush();           // 不会更新这个 product

clear() 会清空 EntityManager 当前管理的全部实体:

$em->clear();

批量导入数据时经常会用到它,避免内存持续上涨。

批量写入示例

一次导入几万条数据时,不适合每一条都 flush()

可以分批提交:

publicfunction importProducts(Category $category, array $rows, EntityManagerInterface $em): void{    foreach ($rows as $index => $row) {        $product = new Product();        $product->setName($row['name']);        $product->setPrice((int) $row['price']);        $product->setStock((int) $row['stock']);        $product->setCategory($category);        $em->persist($product);        if (($index + 1) % 500 === 0) {            $em->flush();            $em->clear();        }    }    $em->flush();    $em->clear();}

这里的关键点:

每 500 条 flush 一次,把 SQL 分批提交。每次提交后 clear,释放 EntityManager 对已管理对象的引用。

如果 Category 在 clear() 后还要继续使用,需要重新查询或改成只保存 category_id 的批处理写法。

常用字段类型

Doctrine 常见字段类型:

类型
PHP 类型
数据库含义
stringstring
VARCHAR
textstring
TEXT
integerint
INT
bigintstring/int
BIGINT,不同平台表现略有差异
booleanbool
BOOLEAN / TINYINT
decimalstring
DECIMAL,常用于金额
floatfloat
浮点数
datetimeDateTimeInterface
可变日期时间
datetime_immutableDateTimeImmutable
不可变日期时间
jsonarray
JSON

示例:

use Doctrine\DBAL\Types\Types;#[ORM\Column(type: Types::DECIMAL, precision: 10, scale: 2)]private string $amount = '0.00';#[ORM\Column(type: Types::JSON)]private array $extra = [];#[ORM\Column(type: Types::DATETIME_IMMUTABLE)]private \DateTimeImmutable $createdAt;

金额字段有两种常见处理方式:

1. 使用 integer 保存分,计算简单,适合大多数业务。2. 使用 decimal 保存小数,注意 Doctrine 中通常映射为 string。

常用映射属性

属性
作用
#[ORM\Entity]
声明实体类
#[ORM\Table]
指定表名、索引、唯一约束
#[ORM\Id]
声明主键
#[ORM\GeneratedValue]
主键生成策略
#[ORM\Column]
字段映射
#[ORM\ManyToOne]
多对一
#[ORM\OneToMany]
一对多
#[ORM\OneToOne]
一对一
#[ORM\ManyToMany]
多对多
#[ORM\JoinColumn]
外键列配置
#[ORM\JoinTable]
多对多中间表配置

索引和唯一约束示例:

#[ORM\Entity(repositoryClass: ProductRepository::class)]#[ORM\Table(name: 'product')]#[ORM\Index(columns: ['created_at'], name: 'idx_product_created_at')]#[ORM\UniqueConstraint(columns: ['name'], name: 'uniq_product_name')]class Product{}

生命周期回调

生命周期回调适合处理创建时间、更新时间这类通用字段。

#[ORM\Entity]#[ORM\HasLifecycleCallbacks]class Article{    #[ORM\Id]    #[ORM\GeneratedValue]    #[ORM\Column]    private ?int $id = null;    #[ORM\Column]    private \DateTimeImmutable $createdAt;    #[ORM\Column(nullable: true)]    private ?\DateTimeImmutable $updatedAt = null;    #[ORM\PrePersist]    publicfunction onPrePersist(): void{        $this->createdAt = new \DateTimeImmutable();    }    #[ORM\PreUpdate]    publicfunction onPreUpdate(): void{        $this->updatedAt = new \DateTimeImmutable();    }}

常见回调:

回调
时机
PrePersist
新实体写入前
PostPersist
新实体写入后
PreUpdate
实体更新前
PostUpdate
实体更新后
PreRemove
删除前
PostRemove
删除后
PostLoad
实体从数据库加载后

如果逻辑比较复杂,更适合使用事件监听器或订阅器,避免实体类变得过重。

原生 SQL 查询

Doctrine 不限制使用原生 SQL。

复杂报表、特殊数据库函数、性能要求很高的查询,可以直接使用 DBAL:

$connection = $em->getConnection();$rows = $connection->fetchAllAssociative(    'SELECT category_id, COUNT(*) AS total_count     FROM product     WHERE stock > :stock     GROUP BY category_id',    ['stock' => 0]);

返回结果是数组,不是实体对象。

如果查询结果只是统计报表,数组通常更直接。

乐观锁示例

并发更新同一条数据时,可以加版本字段。

#[ORM\Column]#[ORM\Version]private int $version = 1;

当两个请求同时读取同一个商品并修改库存时,Doctrine 会在更新时检查版本。

版本不一致时,会抛出乐观锁异常。

这种方式适合低冲突并发场景。高并发扣库存还需要结合数据库锁、队列、Redis、库存冻结等方案。

常见问题

修改了实体,数据库表没有变化

实体类只是映射定义,不会自动改表。

需要执行:

php bin/console make:migrationphp bin/console doctrine:migrations:migrate

修改对象后没有更新数据库

常见原因是没有调用:

$em->flush();

还有一种情况是对象已经脱离 EntityManager 管理,例如执行过 clear() 或 detach()

findBy 只能写等值条件

例如:

$repository->findBy(['price' => 10000]);

这表示 price = 10000

如果需要 price > 10000,使用 QueryBuilder

$repository->createQueryBuilder('p')    ->andWhere('p.price > :price')    ->setParameter('price', 10000)    ->getQuery()    ->getResult();

关联对象访问时查询次数很多

列表场景中,如果循环访问关联对象,容易出现大量额外查询。

可以使用:

->innerJoin('p.category', 'c')->addSelect('c')

提前把关联对象查出来。

批量导入内存越来越高

EntityManager 会持有已管理实体引用。

批量写入时建议分批:

if (($index + 1) % 500 === 0) {    $em->flush();    $em->clear();}

Doctrine 的使用边界

Doctrine 很适合:

  • • 标准业务 CRUD
  • • 实体关系清晰的项目
  • • 后台管理系统
  • • 需要数据库迁移管理的项目
  • • 需要 Repository 封装查询逻辑的项目
  • • 需要事务包裹多个实体变更的业务

以下场景可以混合使用 DBAL 或原生 SQL:

  • • 大型报表统计
  • • 极复杂 SQL
  • • 大批量更新
  • • 对 SQL 执行计划要求很细的查询
  • • 只需要返回数组、不需要实体对象的查询

比较实用的做法是:

常规业务用 ORM。复杂查询用 QueryBuilder 或 DQL。报表和批处理用 DBAL 或原生 SQL。

总结

Doctrine 的核心不是把 SQL 藏起来,而是把数据库操作组织成更稳定的对象模型。

最重要的几条主线:

  • • Entity 负责描述表和字段
  • • Repository 负责封装查询
  • • EntityManager 负责管理对象状态
  • • persist() 用于登记新对象
  • • flush() 才是真正提交变更
  • • Migration 负责把实体结构同步到数据库
  • • QueryBuilder 适合复杂条件查询
  • • 事务适合包裹一组必须同时成功的业务操作

掌握这些主线后,Doctrine 就不只是一个 CRUD 工具,而是 PHP 项目里组织数据访问层的一套完整方案。

最新文章

随机文章

基本 文件 流程 错误 SQL 调试
  1. 请求信息 : 2026-07-02 21:55:00 HTTP/2.0 GET : https://f.mffb.com.cn/a/499286.html
  2. 运行时间 : 0.265142s [ 吞吐率:3.77req/s ] 内存消耗:4,876.60kb 文件加载:140
  3. 缓存信息 : 0 reads,0 writes
  4. 会话信息 : SESSION_ID=87ca4488dafc522fafc1e378706e9e83
  1. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/public/index.php ( 0.79 KB )
  2. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/autoload.php ( 0.17 KB )
  3. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/composer/autoload_real.php ( 2.49 KB )
  4. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/composer/platform_check.php ( 0.90 KB )
  5. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/composer/ClassLoader.php ( 14.03 KB )
  6. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/composer/autoload_static.php ( 4.90 KB )
  7. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/helper.php ( 8.34 KB )
  8. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-validate/src/helper.php ( 2.19 KB )
  9. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/helper.php ( 1.47 KB )
  10. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/stubs/load_stubs.php ( 0.16 KB )
  11. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Exception.php ( 1.69 KB )
  12. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-container/src/Facade.php ( 2.71 KB )
  13. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/symfony/deprecation-contracts/function.php ( 0.99 KB )
  14. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/symfony/polyfill-mbstring/bootstrap.php ( 8.26 KB )
  15. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/symfony/polyfill-mbstring/bootstrap80.php ( 9.78 KB )
  16. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/symfony/var-dumper/Resources/functions/dump.php ( 1.49 KB )
  17. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-dumper/src/helper.php ( 0.18 KB )
  18. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/symfony/var-dumper/VarDumper.php ( 4.30 KB )
  19. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/App.php ( 15.30 KB )
  20. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-container/src/Container.php ( 15.76 KB )
  21. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/psr/container/src/ContainerInterface.php ( 1.02 KB )
  22. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/provider.php ( 0.19 KB )
  23. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Http.php ( 6.04 KB )
  24. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/helper/Str.php ( 7.29 KB )
  25. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Env.php ( 4.68 KB )
  26. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/common.php ( 0.03 KB )
  27. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/helper.php ( 18.78 KB )
  28. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Config.php ( 5.54 KB )
  29. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/app.php ( 0.95 KB )
  30. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/cache.php ( 0.78 KB )
  31. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/console.php ( 0.23 KB )
  32. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/cookie.php ( 0.56 KB )
  33. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/database.php ( 2.48 KB )
  34. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/facade/Env.php ( 1.67 KB )
  35. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/filesystem.php ( 0.61 KB )
  36. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/lang.php ( 0.91 KB )
  37. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/log.php ( 1.35 KB )
  38. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/middleware.php ( 0.19 KB )
  39. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/route.php ( 1.89 KB )
  40. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/session.php ( 0.57 KB )
  41. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/trace.php ( 0.34 KB )
  42. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/view.php ( 0.82 KB )
  43. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/event.php ( 0.25 KB )
  44. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Event.php ( 7.67 KB )
  45. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/service.php ( 0.13 KB )
  46. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/AppService.php ( 0.26 KB )
  47. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Service.php ( 1.64 KB )
  48. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Lang.php ( 7.35 KB )
  49. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/lang/zh-cn.php ( 13.70 KB )
  50. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/initializer/Error.php ( 3.31 KB )
  51. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/initializer/RegisterService.php ( 1.33 KB )
  52. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/services.php ( 0.14 KB )
  53. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/service/PaginatorService.php ( 1.52 KB )
  54. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/service/ValidateService.php ( 0.99 KB )
  55. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/service/ModelService.php ( 2.04 KB )
  56. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-trace/src/Service.php ( 0.77 KB )
  57. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Middleware.php ( 6.72 KB )
  58. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/initializer/BootService.php ( 0.77 KB )
  59. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/Paginator.php ( 11.86 KB )
  60. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-validate/src/Validate.php ( 63.20 KB )
  61. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/Model.php ( 23.55 KB )
  62. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/Attribute.php ( 21.05 KB )
  63. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/AutoWriteData.php ( 4.21 KB )
  64. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/Conversion.php ( 6.44 KB )
  65. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/DbConnect.php ( 5.16 KB )
  66. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/ModelEvent.php ( 2.33 KB )
  67. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/RelationShip.php ( 28.29 KB )
  68. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/contract/Arrayable.php ( 0.09 KB )
  69. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/contract/Jsonable.php ( 0.13 KB )
  70. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/contract/Modelable.php ( 0.09 KB )
  71. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Db.php ( 2.88 KB )
  72. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/DbManager.php ( 8.52 KB )
  73. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Log.php ( 6.28 KB )
  74. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Manager.php ( 3.92 KB )
  75. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/psr/log/src/LoggerTrait.php ( 2.69 KB )
  76. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/psr/log/src/LoggerInterface.php ( 2.71 KB )
  77. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Cache.php ( 4.92 KB )
  78. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/psr/simple-cache/src/CacheInterface.php ( 4.71 KB )
  79. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/helper/Arr.php ( 16.63 KB )
  80. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/cache/driver/File.php ( 7.84 KB )
  81. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/cache/Driver.php ( 9.03 KB )
  82. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/contract/CacheHandlerInterface.php ( 1.99 KB )
  83. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/Request.php ( 0.09 KB )
  84. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Request.php ( 55.78 KB )
  85. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/middleware.php ( 0.25 KB )
  86. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Pipeline.php ( 2.61 KB )
  87. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-trace/src/TraceDebug.php ( 3.40 KB )
  88. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/middleware/SessionInit.php ( 1.94 KB )
  89. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Session.php ( 1.80 KB )
  90. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/session/driver/File.php ( 6.27 KB )
  91. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/contract/SessionHandlerInterface.php ( 0.87 KB )
  92. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/session/Store.php ( 7.12 KB )
  93. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Route.php ( 23.73 KB )
  94. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/RuleName.php ( 5.75 KB )
  95. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/Domain.php ( 2.53 KB )
  96. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/RuleGroup.php ( 22.43 KB )
  97. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/Rule.php ( 26.95 KB )
  98. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/RuleItem.php ( 9.78 KB )
  99. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/route/app.php ( 1.72 KB )
  100. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/facade/Route.php ( 4.70 KB )
  101. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/dispatch/Controller.php ( 4.74 KB )
  102. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/Dispatch.php ( 10.44 KB )
  103. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/controller/Index.php ( 4.81 KB )
  104. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/BaseController.php ( 2.05 KB )
  105. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/facade/Db.php ( 0.93 KB )
  106. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/connector/Mysql.php ( 5.44 KB )
  107. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/PDOConnection.php ( 52.47 KB )
  108. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/Connection.php ( 8.39 KB )
  109. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/ConnectionInterface.php ( 4.57 KB )
  110. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/builder/Mysql.php ( 16.58 KB )
  111. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/Builder.php ( 24.06 KB )
  112. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/BaseBuilder.php ( 27.50 KB )
  113. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/Query.php ( 15.71 KB )
  114. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/BaseQuery.php ( 45.13 KB )
  115. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/TimeFieldQuery.php ( 7.43 KB )
  116. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/AggregateQuery.php ( 3.26 KB )
  117. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/ModelRelationQuery.php ( 20.07 KB )
  118. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/ParamsBind.php ( 3.66 KB )
  119. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/ResultOperation.php ( 7.01 KB )
  120. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/WhereQuery.php ( 19.37 KB )
  121. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/JoinAndViewQuery.php ( 7.11 KB )
  122. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/TableFieldInfo.php ( 2.63 KB )
  123. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/Transaction.php ( 2.77 KB )
  124. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/log/driver/File.php ( 5.96 KB )
  125. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/contract/LogHandlerInterface.php ( 0.86 KB )
  126. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/log/Channel.php ( 3.89 KB )
  127. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/event/LogRecord.php ( 1.02 KB )
  128. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/Collection.php ( 16.47 KB )
  129. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/facade/View.php ( 1.70 KB )
  130. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/View.php ( 4.39 KB )
  131. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Response.php ( 8.81 KB )
  132. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/response/View.php ( 3.29 KB )
  133. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Cookie.php ( 6.06 KB )
  134. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-view/src/Think.php ( 8.38 KB )
  135. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/contract/TemplateHandlerInterface.php ( 1.60 KB )
  136. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-template/src/Template.php ( 46.61 KB )
  137. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-template/src/template/driver/File.php ( 2.41 KB )
  138. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-template/src/template/contract/DriverInterface.php ( 0.86 KB )
  139. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/runtime/temp/067d451b9a0c665040f3f1bdd3293d68.php ( 11.98 KB )
  140. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-trace/src/Html.php ( 4.42 KB )
  1. CONNECT:[ UseTime:0.000807s ] mysql:host=127.0.0.1;port=3306;dbname=f_mffb;charset=utf8mb4
  2. SHOW FULL COLUMNS FROM `fenlei` [ RunTime:0.001434s ]
  3. SELECT * FROM `fenlei` WHERE `fid` = 0 [ RunTime:0.006716s ]
  4. SELECT * FROM `fenlei` WHERE `fid` = 63 [ RunTime:0.003760s ]
  5. SHOW FULL COLUMNS FROM `set` [ RunTime:0.001409s ]
  6. SELECT * FROM `set` [ RunTime:0.000471s ]
  7. SHOW FULL COLUMNS FROM `article` [ RunTime:0.001510s ]
  8. SELECT * FROM `article` WHERE `id` = 499286 LIMIT 1 [ RunTime:0.002563s ]
  9. UPDATE `article` SET `lasttime` = 1783000500 WHERE `id` = 499286 [ RunTime:0.042408s ]
  10. SELECT * FROM `fenlei` WHERE `id` = 64 LIMIT 1 [ RunTime:0.001734s ]
  11. SELECT * FROM `article` WHERE `id` < 499286 ORDER BY `id` DESC LIMIT 1 [ RunTime:0.011522s ]
  12. SELECT * FROM `article` WHERE `id` > 499286 ORDER BY `id` ASC LIMIT 1 [ RunTime:0.027995s ]
  13. SELECT * FROM `article` WHERE `id` < 499286 ORDER BY `id` DESC LIMIT 10 [ RunTime:0.025684s ]
  14. SELECT * FROM `article` WHERE `id` < 499286 ORDER BY `id` DESC LIMIT 10,10 [ RunTime:0.023985s ]
  15. SELECT * FROM `article` WHERE `id` < 499286 ORDER BY `id` DESC LIMIT 20,10 [ RunTime:0.010951s ]
0.266648s