php - Laravel Eloquent : belongsTo relationship - Error: Trying to get property of non-object

标签 php laravel

第一次尝试laravel eloquent relatioinstip

我知道这很简单,但我收到这个错误,不知道它出了什么问题

我在数据库中有 2 个表,news 和 news_image

在数据库中

表格:

news  
id | header | details 

news_image
id | image | news_id 

并且有 2 个模型 News , newsImage

新闻图像模型:

 class newsImage extends Eloquant {

    protected $table = 'news_image';
    public function news()
    {
        return $this->belongsTo('News');
    }    
}

新闻模型

class News extends Eloquent 
{

    protected $table = 'news';

    public $timestamps = false;


    public function image()
    {
        return $this->hasMany('newsImage');
    }


}

View :

foreach($news as $new)
<tr>
   <td> {{$new->id}} </td>
   <td> {{ $new->header}}</td>
   <td> {{ $new->details }}</td>
   </td> {{$new->news->image}}</td>
</tr>

当我运行它时出现错误:

Trying to get property of non-object (View: /var/www/html/clinics/app/views/news/index.blade.php)

关于可能导致此错误的原因有什么想法吗?

最佳答案

首先,假设您传递给 View 的是 News 的数组或集合对象,你可能应该使用 $new->image访问 News Item关系。通过定义函数 image()在你的News模型,您可以使用 ->image 访问关系或 ->image()电话。无论哪种情况,您需要调用的可能是

$new->image->first()->image

分解一下:

  • ->image获取 NewsImage 的集合关系
  • ->first()获取集合中的第一项
  • ->image (第二个)从 NewsImage 获取图像字段

如果集合有多个项目,您可以循环遍历它以获取其他答案中显示的所有图像。

关于php - Laravel Eloquent : belongsTo relationship - Error: Trying to get property of non-object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30943344/

相关文章:

php - 导出 csv 文件以使用 PHP 从 mysql 下载

拉拉维尔 : Pass information with key in url

php - Laravel,使用中间件查找域,然后使用域行获取网站行。

laravel - 如何在 Laravel 中设置 session 之前检查语言是否存在?

php - 根据用户角色过滤菜单项

php - MySql 5.6 组然后遍历每个组

Laravel/lumen 5.2 从现有数据库生成迁移表

php - Laravel multiauth md5 和主键字符串

javascript - 检查下拉菜单并动态更改单元格颜色

php - 转到我在表中的排名