错误如下所示:
Trying to get property of non-object (View: C:'xampp'htdocs'laravel'app'views'singlePost.blade.php)
有 2 个表:评论和用户。在注释表中,有一个名为 user_id 的列,它引用用户表中的 id 列。用户表中有用户名列。 这就是我尝试打印用户名的方式。
@foreach($theComments as $theComment)
<div>{{$theComment->users->username}}</div>
<div style="border:1px solid black;margin:8px 0px 8px 0px">{{$theComment['content']}}</div>
@endforeach
和控制器:
public function singlePost(Posts $post)
{
$id = $post['id'];
$comments = Comments::where('post_id','=',$id)->get();
$users = Users::all();
return View::make('singlePost')->with('thePost', $post)->with('theComments', $comments)->with('theUser', $users);
}
和/模型/注释.php
<?php
class Comments extends Eloquent{
protected $fillable = array('user_id');
public function users(){
return $this->belongsTo('Users');
}
}
问题是什么,我该如何解决?
首先,
我建议您将关系重命名为仅user()
(一开始以为它会返回一个集合)。错误的源可能是未分配用户的注释。
最好的方法是从查询中排除这些内容。您可以使用has()
$comments = Comments::has('user')->where('post_id','=',$id)->get();
并且您还应该急于加载用户关系,否则您会遇到 n+1 查询问题:
$comments = Comments::has('user')->with('user')->where('post_id','=',$id)->get();
编辑
尝试将其包装在您的视图中:
@foreach($theComments as $theComment)
@if($user = $theComment->users)
<div>{{$user->username}}</div>
@endif
@endforeach
您需要先加载关系
$comments = Comments::with('users')->where('post_id','=',$id)->get();
见 http://laravel.com/docs/4.2/eloquent#eager-loading