我见过很多方式教义来实现这一2.
一般情况下,最快捷的方式和大多数用户do在构造函数中需要一个关联。
public function __construct(Foo $foo)
{
$this->foo = $foo;
}
然后你可以使用getReference
在控制器中进行检索,而无需查询数据库。见http://doctrine-orm.readthedocs.org/en/latest/reference/advanced-configuration.html#reference-proxies
$foo = $em->getReference('app:Foo', 1);
$text = new \Path\To\Entity\PublicText($foo);
$em->persist($text);
$em->flush();
我的首选方式来设置与大多数ManyToOne
关系的默认值是利用LifeCycleEvents
http://doctrine-orm.readthedocs.org/en/latest/reference/events.html
虽然它确实有一些注意事项需要注意的。因此,在实施到生产环境之前,请确保RTM。在这种情况下,它应该可以正常工作,但我不知道你的整个映射结构。
use Doctrine\ORM\Event\LifecycleEventArgs;
/**
* @Entity
* @HasLifeCycleEvents
*/
class PublicText
{
// ...
/**
* @PrePersist
* @param \Doctrine\ORM\Event\LifecycleEventArgs $event
*/
public function onPrePersist(LifecycleEventArgs $event)
{
if (false === empty($this->foo)) {
return;
}
$this->foo = $event->getEntityManager()->getReference('app:Foo', 1);
}
}
然后在你的控制器中。
$text = new \Path\To\Entity\PublicText;
$em->persist($text); //retrieve and set foo if not set in the Entity Event.
$em->flush();
你的实体内另一种选择是使用仓库设置属性的值。
定义库类的实体
/**
* @Entity(repositoryClass="PublicTextRepo")
*/
class PublicText
{
// ...
}
库
use Doctrine\ORM\EntityRepository;
class PublicTextRepo extends EntityRepository
{
public function create()
{
$text = new \Path\To\Entity\PublicText;
$foo = $this->_em->getReference('app:Foo', 1);
$text->setFoo($foo);
return $text;
}
}
然后在你的控制器,你就可以做取决于使用
$text = $em->getRepository('app:PublicText')->create();
$em->persist($text);
$em->flush();
虽然并不总是可行的案件。我定义一个实体的默认值的方法之一是创建一个带有单个表继承的DiscriminatorMap
。 http://doctrine-orm.readthedocs.org/en/latest/reference/inheritance-mapping.html#single-table-inheritance。
通过这种方式创建对象时,默认值将在数据库中自动设置,并将该对象锁定为该类型。问题是,结果值是而不是对象,就像它在上面的其他方法中一样。
要获取对象的鉴别器值static
值,可以在定义的对象内使用常量。
/**
* @Entity
* @InheritanceType("SINGLE_TABLE")
* @Table(name="user")
* @DiscriminatorColumn(name="type", type="string")
* @DiscriminatorMap({Person::TYPE="Person", Employee::TYPE="Employee"})
*/
class Person
{
const TYPE = 'person';
/**
* @return Person|Employee
*/
public function getType()
{
return $this::TYPE;
}
// ...
}
/**
* @Entity
*/
class Employee extends Person
{
const TYPE = 'employee';
// ...
}
然后,你需要在你的控制器中做的是。
$employee = new \Path\To\Entity\Employee;
$em->persist($employee); //inserts with `user.type` as `employee`
$em->flush();
echo $employee->getType(); //employee
它不工作:注释@ORM \ JoinColumn ...不有一个名为“选项”的属性 – tudor 2016-08-02 13:18:46