duanqin9507 2015-01-13 13:54
浏览 31
已采纳

尝试使用雄辩关系时尝试获取非对象错误的属性

The error is like below:

Trying to get property of non-object (View: C:\xampp\htdocs\laravel\app\views\singlePost.blade.php)

There is 2 tables: Comments and Users. In comments table there is a column named user_id and that refers to id column that is in users table. And there is username column in the users table. This is how I try to print username.

@foreach($theComments as $theComment)
<div>{{$theComment->users->username}}</div>
<div style="border:1px solid black;margin:8px 0px 8px 0px">{{$theComment['content']}}</div>
@endforeach

and controller:

 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);
    }

and /Model/Comments.php

<?php
class Comments extends Eloquent{
    protected $fillable = array('user_id');
    public function users(){
        return $this->belongsTo('Users');
    }
}

What's the problem and how can i solve it?

  • 写回答

2条回答 默认 最新

  • duanhe6718 2015-01-13 14:00
    关注

    First I suggest you rename the relationship to just user() (At the beginning thought it would return a collection). The source of the error is probably a comment that has no user assigned.

    The best way would just be to exclude those from your query. You can use has() for that

    $comments = Comments::has('user')->where('post_id','=',$id)->get();
    

    And you should also eager load the user relationship, otherwise you have a n+1 queries issue:

    $comments = Comments::has('user')->with('user')->where('post_id','=',$id)->get();
    

    Edit

    Try wrapping this if around it in your view:

    @foreach($theComments as $theComment)
        @if($user = $theComment->users)
            <div>{{$user->username}}</div>
        @endif
    @endforeach
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?