dongying3830 2014-08-22 20: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 20: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条)

报告相同问题?

悬赏问题

  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数