Posts

Showing posts with the label Doctrine

Removing Related Entities in Doctrine

The article shows what options need to set for removing related entities in Doctrine. Doctrine has several options for removing related entities: cascade=["remove"] orphanRemoval=true onDelete="CASCADE | SET NULL" Doctrine wraps INSERT , UPDATE , DELETE SQL statements in a transaction by default. cascade=["remove"] When cascade: ['remove'] is specified, remove will also be executed on the associated entity. Doesn't require creating a migration as there are no changes to the database schema. OneToOne #[ORM\Entity(repositoryClass: ProductRepository::class)] class Product { #[ORM\OneToOne(mappedBy: 'product', cascade: ['remove'])] private ?Photo $photo = null; } #[ORM\Entity(repositoryClass: PhotoRepository::class)] class Photo { #[ORM\OneToOne(inversedBy: 'photo')] #[ORM\JoinColumn(nullable: false)] private ?Product $product = null; } FOREIGN KEY is set on the side of the ...

Doctrine Query Builder Optimization

The article describes how to reduce the number of Doctrine generated SQL queries when using Query Builder. The Product entity, which has the required Brand and Category entities and the optional Photo entity: #[ORM\Entity(repositoryClass: ProductRepository::class)] class Product { #[ORM\ManyToOne()] #[ORM\JoinColumn(nullable: false)] private ?Brand $brand = null; #[ORM\ManyToOne(inversedBy: 'products')] #[ORM\JoinColumn(nullable: false)] private ?Category $category = null; #[ORM\OneToOne()] private ?Photo $photo = null; } Product entity repository: class ProductRepository extends ServiceEntityRepository { public function findByCategoryId(int $categoryId): array { return $this->createQueryBuilder('p') ->andWhere('p.category = :categoryId') ->setParameter('categoryId', $categoryId) ->getQuery() ->getResult() ; } } Gettin...