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');
      }
      ...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元