douhe3313 2013-01-11 20:38
浏览 51
已采纳

尝试访问Laravel 4中的关系数据时出错

I've been using Laravel 4 for a few days now and I stumbled across something I can't seem to fix.

Using Eloquent, I've set up 2 models, where Appointment has a belongsTo relationship to Room. After retrieving it like so (using eager loading):

$appointments = Appointment::with('room')->get();

I'm printing it in my view: http://paste.laravel.com/fnL

I loop through it and retrieve a value of Appointment:

@foreach($appointments as $appointment)
    <tr>
        <td>{{ $appointment->begins_at }}</td>
        <td>
            <a href="/admin/appointments/delete/{{ $appointment->id }}" class="btn btn-mini btn-danger">Verwijderen</a>
        </td>
    </tr>
@endforeach

This works fine, but when I add the following line:

<td>{{ $appointment->room->name }}</td>

It throws the following error:

ErrorException: Notice: Trying to get property of non-object

I'm probably just overlooking something, but I've been looking at it for quite some time and I just don't see it...

Thanks in advance for any help!

  • 写回答

1条回答 默认 最新

  • dquh37673 2013-01-11 20:44
    关注

    The second appointment in the collection does not have a room, thus, $appointment->room is null, so You are essentially doing null->name

    enter image description here

    Solution is to check if the room is set.

    @if($appointment->room)
        {{ $appointment->room->name }}
    @endif
    

    Hope that helps

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 STM32 INMP441无法读取数据
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。
  • ¥15 各位 帮我看看如何写代码,打出来的图形要和如下图呈现的一样,急
  • ¥30 c#打开word开启修订并实时显示批注
  • ¥15 如何解决ldsc的这条报错/index error
  • ¥15 VS2022+WDK驱动开发环境