Twig 和 Symfony2 - 未找到实体

2022-01-03 00:00:00 php symfony doctrine-orm entity

我有一个与其他一些实体相关的实体.最后,我有一个像 tat 这样的对象:

I have an entity that is related to some other entities. On the end, I have an object like tat:

paper.submission.authors

对于一些paper.submission,没有作者,在我的twig模板中,我在做:

For some of the paper.submission, there is no author, and in my twig template, I am doing:

{% for author in paper.submission.authors}
    do something
{% endfor %}

对于没有作者的 paper.submission,我收到实体未找到"异常.

And for the paper.submission with no authors, I am getting "Entity was not found" exception.

你是否有可能在我的 for 循环之前测试对象是否存在.

Is thee any possibility to test if the object exists before my for loop.

我尝试过定义,它总是正确的.然后,我尝试过不为空,但这也会产生异常.

I have try the is defined, it is always true. Then, I have tryed is not null, but this is also generating the exception.

非常感谢您.

推荐答案

问题

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

相关文章