dongying3830 2014-08-22 12:11
浏览 50
已采纳

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

展开全部

  • 写回答

2条回答 默认 最新

  • douluyezhen4512 2014-08-22 12:32
    关注

    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 %}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部