我有以下类(只显示部分以减少读取量)
class Page {
/**
* @ORM'Column(type="string", unique=true, nullable=false)
* @ORM'Id
* @ORM'GeneratedValue(strategy="UUID")
* @var string
*/
protected $id;
/**
* @ORM'OneToMany(targetEntity="Url", mappedBy="content")
* @var Url[]
*/
protected $urls;
public function __construct()
{
$this->urls = new ArrayCollection();
}
}
和:
class Url
{
/**
* @ORM'Id @ORM'Column(type="string", unique=true, nullable=false)
* @ORM'GeneratedValue(strategy="UUID")
* @var string The unique identifier for the Url
*/
protected $id;
/**
* @ORM'ManyToOne(targetEntity="Page", inversedBy="urls", cascade={"persist", "merge"})
* @ORM'JoinColumn(name="content_id", referencedColumnName="id")
* @var int The UUID of the content
*/
protected $content;
public function __construct(Page $content, $link)
{
$this->content = $content;
$this->content->addUrl($this);
}
}
其中每一个都有一个带有save()
函数的管理器类,该函数只使用persist()
和flush()
。然后将它们保存为:
$pageManager->save($post);
$url = new Url($post, 'link goes here');
$urlManager->save($url);
我也试过:
$url = new Url($post, 'link goes here');
$pageManager->save($post);
$urlManager->save($url);
尽管在这两种情况下我都得到:
(!)致命错误:未捕获异常"Doctrine''ORM''ORMInvalidArgumentException",消息为"托管+脏实体"Page@000000003d5a4ca10000000133ba3c3e无法安排插入。'
我已经尝试过使用和不使用AnnotationReader
与EntityManager::create()
一起使用
Doctrine的模式验证器也不会报告任何错误:
php vendor/bin/doctrine orm:validate-schema
[Mapping] OK - The mapping files are correct.
[Database] OK - The database schema is in sync with the mapping files.
有什么想法可以让persist()
工作吗?
弄明白了:
我不得不颠倒它们的保存顺序,所以先保存Url
,然后保存Page
(尽管这样做会带来另一个问题,我需要解决它想保留作者实体但不能(它认为这是新的,但事实并非如此)。我想也许它是分离的,但即使是merge()
也无法解决它
/**
* @ORM'ManyToOne(targetEntity="User")
* @ORM'JoinColumn(name="author_id", referencedColumnName="id")
* @var string The UUID of the author for the {@link Page}
*/
protected $author;
必须在flush()
之前持久化$post
和$url
对象。否则,您将收到此错误消息。
试着这样做。。。
$entityManager->persist($post);
$url = new Url($post, 'link goes here');
$entityManager->persist($url);
$entityManager->flush();
或者,您可以在管理器上创建一个标志参数,如果为false,则不刷新。。。
$flush = false;
$pageManager->save($post, $flush);
$url = new Url($post, 'link goes here');
$urlManager->save($url);
它可能在没有任何额外资源的情况下工作。