Twig and Symfony2 - Entity was not found

2019-01-25 05:28发布

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

paper.submission.authors

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 %}

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

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.

Thank you very much in advance.

3条回答
虎瘦雄心在
2楼-- · 2019-01-25 05:59

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.

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.

What happens

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

var_dump($submission->getAuthors());

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) {
}

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;

Which returns no match and will throw an EntityNotFound Exception

Fix

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 will not run any query if it finds a NULL

查看更多
该账号已被封号
3楼-- · 2019-01-25 06:17

How to debug to find which related entity was not found?

Exception message improved in repository https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/Proxy/ProxyFactory.php#L160 but if you use older version you can do the following debugging.

If you use older version

Put following code to ProxyFactory class before throw new EntityNotFoundException(); line vendor/doctrine/orm/lib/Doctrine/ORM/Proxy/ProxyFactory.php:177

$entity = $classMetadata->getReflectionClass()->getShortName();
$id = $classMetadata->getIdentifierValues($proxy)['id'];
var_dump("$entity WHERE id = $id NOT FOUND.");exit;
throw new EntityNotFoundException();
查看更多
戒情不戒烟
4楼-- · 2019-01-25 06:18

In your entity you can made something like this:

public function getSubmission(){
    if($this->Submission->getId()==0) return null;
    return $this->Submission;
}
查看更多
登录 后发表回答