草庐IT

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

coder 2024-04-14 原文

第一次尝试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 - Laravel Eloquent : belongsTo relationship - Error: Trying to get property of non-object的更多相关文章

随机推荐