我可以设置一个简单的默认值,例如字符串或布尔值,但我找不到如何设置实体的默认值。
在我的 User.php 实体中:
/**
* @ORM\ManyToOne(targetEntity="Acme\DemoBundle\Entity\Foo")
*/
protected $foo;
在构造函数中,我需要为 $foo 设置默认值:
public function __construct()
{
parent::__construct();
$this->foo = 1; // set id to 1
}
需要一个 Foo 对象,它传递一个整数。
设置默认实体 ID 的正确方法是什么?
我认为你最好将其设置在PrePersist
event.
In User.php
:
use Doctrine\ORM\Mapping as ORM;
/**
* ..
* @ORM\HasLifecycleCallbacks
*/
class User
{
/**
* @ORM\PrePersist()
*/
public function setInitialFoo()
{
//Setting initial $foo value
}
}
但设置关系值并不是通过设置整数来进行的id
,而是通过添加一个实例来执行Foo
。这可以在事件侦听器内完成,比实体的更好LifecycleCallback
事件(因为你必须打电话Foo
实体的存储库)。
首先,在您的捆绑包中注册事件services.yml
file:
services:
user.listener:
class: Tsk\TestBundle\EventListener\FooSetter
tags:
- { name: doctrine.event_listener, event: prePersist }
And the FooSetter
class:
namespace Tsk\TestBundle\EventListener\FooSetter;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Tsk\TestBundle\Entity\User;
class FooSetter
{
public function prePersist(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
$entityManager = $args->getEntityManager();
if ($entity instanceof User) {
$foo = $entityManager->getRepository("TskTestBundle:Foo")->find(1);
$entity->addFoo($foo);
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)