duanqin9507 2015-01-13 05: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 06: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部