且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Twig 和 Symfony2 - 未找到实体

更新时间:2023-11-19 18:23:28

问题

Doctrine 在找不到相关实体时抛出此异常.这样说似乎多余,但实际上这很重要.
这意味着它可以找到与之相关的 ID,但是提出的请求原则与任何结果都不匹配.

Problem

Doctrine throws this Exception when it doesn't find the related entity. It seems redundant to say this, but in fact this is important.
It means it could find an ID related to it, but the request doctrine made didn't match any result.

我的猜测是您的数据库表(实际上是链接表)submission.authors 包含 0 而不是 NULL 的 ID.
这样,Doctrine 认为IS 有一个 ID 为 0 的作者,因此找不到它.

My guess is that your database table (link table actually) submission.authors contains IDs of 0 instead of NULL.
With such, Doctrine thinks there IS an author with ID of 0, and therefor, cannot find it.

submission.authors 始终存在.它是一个 未初始化 Doctrine 代理.

submission.authors always exists. It is an Uninitialized Doctrine Proxy.

var_dump($submission->getAuthors());

会告诉你什么包含了 submission.authors
此时,不进行任何查询.它只是返回一个 PersistentCollection 带有标志 isInitialized 为假.

Would show you what contains exactly submission.authors
At this point, no queries are made. It simply returns a PersistentCollection with a flag isInitialized to false.

当您尝试从中获取属性时会发生异常

The exception occurs when you're trying to get a property out of it

foreach ($submission->getAuthors() as $author) {
}

执行此操作时将检查 getAuthors 是否已初始化.如果没有,它将运行以下查询

When doing this doctrine will check if getAuthors is initialized. If not, it will run the following query

SELECT <stuffs> FROM authors WHERE id = 0;

不返回匹配项并抛出 EntityNotFound 异常

Which returns no match and will throw an EntityNotFound Exception

您必须将 id 行的默认值设置为 NULL 并进行查询以将所有 0 更新为 NULL.
有了这个,您可以轻松地使用 is not null

You must set your id row's default to NULL and make a query to update all 0's to NULL.
With this, you can easily test submission.authors with is not null

Doctrine 如果发现 NULL

Doctrine will not run any query if it finds a NULL