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 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题