duanhuang1699 2015-09-05 14:30
浏览 78
已采纳

Laravel 5.1:试图通过关系获取foreach循环中非对象的属性

I am trying to loop through a related model to my Users table call AdminNotes using a foreach in my blade view. However, I am getting the following error. Any ideas?

Trying to get property of non-object (View: /home/vagrant/Code/sass_l5/resources/views/users/edit.blade.php)

at HandleExceptions->handleError('8', 'Trying to get property of non-object', '/home/vagrant/Code/sass_l5/storage/framework/views/5da731c9bf1a02452259c329d3c273e0', '226', array('__path' => '/home/vagrant/Code/sass_l5/storage/framework/views/5da731c9bf1a02452259c329d3c273e0', '__data' => array('__env' => object(Factory), 'app' => object(Application), 'errors' => object(ViewErrorBag), 'user' => object(User)), 'obLevel' => '1', '__env' => object(Factory), 'app' => object(Application), 'errors' => object(ViewErrorBag), 'user' => object(User), 'note' => true)) in 5da731c9bf1a02452259c329d3c273e0 line 226

I have the relationships set up like this:

User Model:

...
class User extends Model
{
    ...
    public function adminNotes()
    {
        return $this->hasOne('sass\AdminNote');
    }
    ...
}

AdminNote Model:

...
class AdminNote extends Model {
  ...
  public function user()
  {
    return $this->belongsTo('sass\User');
  }
  ...
}

edit.blade.php

...
@if (count($user->adminNotes) >= 1)
  @foreach ($user->adminNotes as $note)
    {{ $note->created_at }}
    {{ $note->notes }}
  @endforeach
@else
...

dd($user->adminNotes):

AdminNote {#274 ▼


#connection: null
  #table: null
  #primaryKey: "id"
  #perPage: 15
  +incrementing: true
  +timestamps: true
  #attributes: array:5 [▼
    "id" => 25
    "user_id" => 1
    "notes" => "Test note"
    "created_by" => 1
    "created_at" => "2014-01-01 00:00:00"
  ]
  #original: array:5 [▼
    "id" => 25
    "user_id" => 1
    "notes" => "Test note"
    "created_by" => 1
    "created_at" => "2014-01-01 00:00:00"
  ]
  #relations: []
  #hidden: []
  #visible: []
  #appends: []
  #fillable: []
  #guarded: array:1 [▶]
  #dates: []
  #dateFormat: null
  #casts: []
  #touches: []
  #observables: []
  #with: []
  #morphClass: null
  +exists: true
  +wasRecentlyCreated: false
}

dd($note)

true
  • 写回答

1条回答 默认 最新

  • dounai9592 2015-09-05 14:47
    关注

    Thanks to Ross Wilson for pointing out that my relationships were set up to only have one note, where in they needed to be set up to have many notes.

    ...
    class User extends Model
    {
      ...
      public function adminNotes()
      {
        return $this->hasMany('sass\AdminNote');
      }
      ...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据