Php 原则2.0缓存和默认值

Php 原则2.0缓存和默认值,php,caching,symfony1,doctrine-orm,Php,Caching,Symfony1,Doctrine Orm,使用原则2.x 如果我的域中的实体映射到只有一行的表,则会出现一些问题-这是为了支持将来的额外复杂性(计划中的-因此不适合YAGNI) 以简单实体为例 Category\Type: type: entity table: category_type id: id: type: integer generator: strategy: AUTO fields: name: type: string 目前在我的应用

使用原则2.x

如果我的域中的实体映射到只有一行的表,则会出现一些问题-这是为了支持将来的额外复杂性(计划中的-因此不适合YAGNI)

以简单实体

为例
Category\Type:
  type: entity
  table: category_type
  id:
    id:
      type: integer
      generator:
        strategy: AUTO
  fields:
    name:
      type: string
目前在我的应用程序中,我只有一个类别类型(名称='regular'),但每次我创建一个新类别(未显示实体-请想象;它与category\type有N:1关系)时,我都需要将一个类型与该类别相关联。这意味着必须从数据库中检索我的单行,然后设置关联

$category = new Category();
$type = $em->getRepository('Category\Type')->findByName('regular');
$category->setType($type);
$em->persist($category);
$em->flush();
我想知道如何避免这样做

如果我只是使用一种新的类型,像这样

$category = new Category();
$type = new Category\Type();
$type->setName('regular');
$category->setType($type);
$category->setId(1); // <-- This gets incremented anyway after the persist is called
$em->persist($category);
$em->flush();
$category=新类别();
$type=新类别\类型();
$type->setName('regular');
$category->setType($type);
$category->setId(1);//(类别);
$em->flush();
然后,条令尝试将类型作为新实体插入(事实上,它失败了,因为名称列在数据库中具有唯一的约束)

我已经试着做了上面的工作,然后使用merge

但同样的事情也发生了

我错过了什么?我如何让条令将新对象视为已存在于数据库中,或者如何在代码级别缓存托管实体


在代码中有效地“缓存”是否不合适?我是否应该使用其他缓存机制之一?

您最初的方法是正确的

$category = new Category();
$type = $em->getRepository('Category\Type')->findByName('regular');
$category->setType($type);
$em->persist($category);
$em->flush();
这就是教义的设计方式


您试图做的是通过将name属性设置为已经存在的内容来获取(查找)对象的实例。这是错误的。这就像给你的孩子打电话叫约翰·列侬,希望他能复活披头士。

我想你不能。创建新对象时,需要与现有对象建立关联
Category\Type
。。。新的一行,它将在DB中创建一个新行,您的关联将指向那里,您必须获取现有的一行。这是原则的设计方式,您使用的是对象实例,而不是DB.Lol中的行,在类比中,我将把它交给其他缓存机制。我会让这个打开一段时间,然后再给你做标记。