我设计Symfony实体的方式正确吗



我有一个名为";产品";它有一些简单的字段,如Name、Description和Price。我想将其用作基础实体,这样我就可以基于此产品实体创建具有完全相同字段的其他实体。我可以很容易地复制整个实体类和存储库文件,并将它们重命名为Product1、Product1Repository等,但我觉得这会重复很多代码。我肯定需要处理Entity的副本,在我的数据库设计中添加另一个属性/列将不起作用。扩展或继承这个类的最佳方法是什么,这样Product2、Product3和ProductN类就可以作为基本类存在,只继承Product1的所有内容,并具有相应的Doctrine Repository?我需要做些什么才能做到这一点?这是我迄今为止的代码:

<?php
namespace AppEntity;
use AppRepositoryProductRepository;
use DoctrineORMMapping as ORM;
/**
* @ORMEntity(repositoryClass=ProductRepository::class)
*/
class Product
{
/**
* @ORMId()
* @ORMGeneratedValue()
* @ORMColumn(type="integer")
*/
private $id;
/**
* @ORMColumn(type="string", length=255)
*/
private $name;
/**
* @ORMColumn(type="string", length=255)
*/
private $description;
/**
* @ORMColumn(type="string", length=255)
*/
private $price;

//Getters and setters here...

谢谢!

为什么不让您的基本实体产品抽象化呢?那么你所有的其他产品都可以扩展它吗?

摘要:

/**
* @ORMEntity(repositoryClass=ProductRepository::class)
*/
abstract class Product
{

产品1:

/**
* @ORMEntity(repositoryClass=Product1Repository::class)
*/
class Product1 extends Product
{

您可以从Doctrine文档中检查类表继承。

基本上,您使用子实体共有的所有字段创建基本实体,然后创建一个鉴别器列,映射该列可以具有的值,这些值将映射到子实体。

<?php
namespace MyProjectModel;
/**
* @Entity
* @InheritanceType("JOINED")
* @DiscriminatorColumn(name="discr", type="string")
* @DiscriminatorMap({"person" = "Person", "employee" = "Employee"})
*/
class Person
{
// ...
}
/** @Entity */
class Employee extends Person
{
// ...
}

通过这种方式,您将拥有一个名为"Person"的列的表;discr";以及您声明的所有其他字段;和一个名为Employee的表,Person.id作为主键和Person的外键,加上您在"中声明的所有字段;"雇员";实体

最新更新