[英]ManyToOne relation with Doctrine against Domain Driven Design
I'm facing to an issue with Doctrine relation and DDD.我面临着 Doctrine 关系和 DDD 的问题。
I already searched a lot but I didn't find a suitable answer.我已经搜索了很多,但没有找到合适的答案。
Let's take a simple example:我们举一个简单的例子:
I have an aggregate Category
and an aggregate Product
.我有一个聚合
Category
和一个聚合Product
。 I would like to have a ManyToOne
relation between Product
and Category
.我想在
Product
和Category
之间建立ManyToOne
关系。
Unfortunately Doctrine makes me add an attribute $category
in my Product
.不幸的是,Doctrine 让我在我的
Product
添加了一个属性$category
。 But as Vaughn Vernon said, aggregate should reference to other aggregate by his identity, not by the aggregate itself.但正如沃恩弗农所说,聚合应该通过他的身份来引用其他聚合,而不是通过聚合本身。
Moreover even if I do this, Doctrine overwrites category_id
to null
if I don't set $category
.此外,即使我这样做,如果我不设置
$category
,Doctrine 也会将category_id
覆盖为null
。
My only solution, at this moment, it's to add category_id field in mapping definition and add foreign key by myself.目前我唯一的解决方案是在映射定义中添加 category_id 字段并自己添加外键。
Is there any other solution ?还有其他解决方案吗?
I suspect you maybe trying to use the wrong tool for the job.我怀疑你可能试图使用错误的工具来完成这项工作。 Doctrine 2 is an Object Relational Manager hence it focuses on objects.
Doctrine 2 是一个对象关系管理器,因此它专注于对象。 If you read through the docs you won't find very much on domain driven design.
如果您通读文档,您将不会在域驱动设计方面找到太多内容。
Given that Doctrine focuses on objects then:鉴于 Doctrine 专注于对象,那么:
$category = $product->getCategory();
Makes perfect sense.很有道理。 It also maps nicely onto how sql is designed to work.
它还很好地映射到 sql 的设计方式。
If you really want a property Product::CategoryId then go ahead and add it.如果你真的想要一个属性 Product::CategoryId 然后继续添加它。 The latest Doctrine even has limited support for value objects.
最新的 Doctrine 甚至对值对象的支持也很有限。
But if you then want to somehow access the actual category object then you will need to add in your own query somehow.但是,如果您想以某种方式访问实际的类别对象,那么您将需要以某种方式添加您自己的查询。 Kind of makes the orm code pretty much useless as you would be handing your own relations.
有点使 orm 代码变得毫无用处,因为您将处理自己的关系。 Maybe drop down to pdo or the database access layer.
也许下拉到 pdo 或数据库访问层。
I have seen a few articles trying to do what you want but they barely manage the simplest cases and are impractical for any kind of production scenarios.我看过一些文章试图做你想做的事,但他们几乎没有管理最简单的案例,而且对于任何类型的生产场景都不切实际。 Especially since DDD implies complex business logic.
特别是因为 DDD 意味着复杂的业务逻辑。
I just would add a property categoryId
to Product
and that's it.我只是将一个属性
categoryId
添加到Product
,就是这样。
So I can't navigate from Product
to Category
directly, but instead I would need the CategoryRepository
to fetch the respective category object, if I need it.因此,我无法直接从
Product
导航到Category
,但如果需要,我需要CategoryRepository
来获取相应的类别对象。
I lose the lazy loading convenience, but the aggregates are separated clean and nice.我失去了延迟加载的便利性,但聚合体分离干净且美观。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.