Symfony2 Doctrine manyToOne EntityNotFoundException

I've just started learning Symfony but have run in to something I can't figure out how to solve.

I have a database table of records which may or may not be linked to a user. One user could have many records but a record doesn't have to be associated to a user

I've used doctrine with yml to create a manyToOne relationship between the 2 tables

user:
        targetEntity: User
        mappedBy: records
        joinColumn:
            name: user_id
            referencedColumnName: id

This works absolutely fine when the record has a user associated with it

The problem occurs when the user_id against the record is set to 0

Symfony loads it as a user object, but when I try to do

{{ record.user.name }}

In my twig template while looping through each record, I get an EntityNotFoundException being thrown

I've tried to do different things like

{% if record.user is null %}

With no luck

The only similar question I've been able to find is this one

Which I know would solve my issue, but as I'm learning Symfony and Doctrine I want to know if writing the SQL myself is my only option or if there is something I'm missing to make this work

I guess I could also create a user with the id of 0 but I would like to learn how this should be done rather than doing something dirty like that

My model does the following to load the records

$repository = $this->doctrine->getRepository('SiteBundle:Records');
$records = $repository->findAll();

This is then passed to my twig template which loops through them for output

Thanks in advance for any input

See https://stackoverflow.com/a/17338761/3574819

Instead of setting the user_id of records that don't have a user to 0, set the user_id to null.

Then you can check whether the user object is null (or perhaps you need to use defined) before accessing its properties.

{% if records.user is not null %}
  {{ records.user.name }}
{% endif %}

You should try this

                {% if records.user is not empty %}
                   {{ records.user.name }}
                 {% endif %}

In stead of "null" , "empty" property woks fine here ..