Laravel 5.1:尝试在具有关系的 foreach 循环中获取 non-object 的 属性

Laravel 5.1: Trying to get property of non-object in foreach loop with relationship

我正在尝试通过相关模型循环到我的用户 table 在我的 blade 视图中使用 foreach 调用 AdminNotes。但是,我收到以下错误。有任何想法吗?

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

我的关系是这样设置的:

用户模型:

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

AdminNote 型号:

...
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

感谢 Ross Wilson 指出我的关系设置为只有一个音符,而在其中需要设置为有多个音符。

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