简体   繁体   English

Doctrine2 可以将对象属性映射到实体表吗?

[英]Can Doctrine2 map an object property to the entities' table?

i'm using Doctrine2 for a project with accounting for the user.我正在将 Doctrine2 用于为用户进行会计处理的项目。 So the user object has a collection of account objects.所以用户对象有一个帐户对象的集合。 These account objects have an accounting period with Datetimes for the start and end of the period.这些科目对象有一个会计期间,期间的开始和结束日期都带有日期时间。

/** @Entity */
class Account
{
    /** @Column(type="datetime") */
    private periodStart;

    /** @Column(type="datetime") */
    private periodEnd;
}

Since I have to add some methods to the account class, that should handle the period, I think it would be good practice to refactor the period properties and put them in their own class with the new methods.由于我必须向帐户类添加一些方法,这些方法应该处理期间,我认为重构期间属性并使用新方法将它们放在自己的类中是一种很好的做法。 something like:就像是:

/** @Entity */
class Account
{
    /** ??? */
    private accountPeriod;
}

/** @Entity */
class AccountPeriod
{
    /** @Column(type="datetime") */
    private periodStart;

    /** @Column(type="datetime") */
    private periodEnd;

    public function doSomething(){...}
}

But then Doctrine2 would create a new table for AccountPeriod.但是 Doctrine2 会为 AccountPeriod 创建一个新表。

What I want is to keep the periodStart and periodEnd columns in the Account table.我想要的是在 Account 表中保留 periodStart 和 periodEnd 列。 I searched for it but couldn't find anything - also I looked at custom types but as I understand they only map simple types but not aggregates.我搜索了它但找不到任何东西 - 我也查看了自定义类型,但据我所知,它们只映射简单类型而不是聚合。

I also want to use these columns in queries so the doctrine column type 'object' is no option.我还想在查询中使用这些列,因此没有选择学说列类型“对象”。

Have somebody done this before, maybe with some trick?以前有人这样做过吗,也许有一些技巧? Or is it just impossible with Doctrine2?或者 Doctrine2 是不可能的?

The answer for the above case is Embeddables :上述案例的答案是Embeddables

Embeddables are classes which are not entities themselves, but are embedded in entities and can also be queried in DQL. Embeddables 是本身不是实体的类,而是嵌入在实体中并且也可以在 DQL 中查询的类。 You'll mostly want to use them to reduce duplication or separating concerns.您主要希望使用它们来减少重复或分离关注点。 Value objects such as date range or address are the primary use case for this feature.日期范围或地址等值对象是此功能的主要用例。

The solution would be something like:解决方案类似于:

/** @Entity */
class Account
{
    /** @Embedded(class = "AccountPeriod") */
    private $accountPeriod;
}

/** @Embeddable */
class AccountPeriod
{
    /** @Column(type="datetime") */
    private periodStart;

    /** @Column(type="datetime") */
    private periodEnd;

    public function doSomething(){...}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM