Laravel Eloquent:belongsTo关系-错误:试图获取非对象的属性 [英] Laravel Eloquent : belongsTo relationship - Error: Trying to get property of non-object

查看:195
本文介绍了Laravel Eloquent:belongsTo关系-错误:试图获取非对象的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

第一次尝试laravel雄辩的relatioinstip

First time to try laravel eloquent relatioinstip

我知道这真的很简单,但是我遇到了这个错误,不知道这是怎么回事

I know it's really simple but I am getting this error don't know what's wrong with it

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

I have 2 tables in data base, news and news_image

在数据库中

表格:

news  
id | header | details 

news_image
id | image | news_id 

有2个模型News,newsImage

And have 2 models News , newsImage

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


}

视图:

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

运行此命令时出现错误:

when I run this it's get error :

试图获取非对象的属性(查看:/var/www/html/clinics/app/views/news/index.blade.php)

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

关于什么可能导致此错误的任何想法?

Any ideas on what could be causing this error?

推荐答案

有几件事我需要更改:

  1. 在新闻"模型中,将关系从图像"更改为图像",因为这是一对多关系.它只是保持代码干净.

  1. In your News model, change the relationship from "image" to "images" since it's a one to many relationship. It just keeps your code clean.

您的视图中的foreach循环应遍历所有新闻模型,但请记住,每个新闻模型都具有多个图像,因此您应在现有循环中包含另一个循环以显示图像,即foreach ($new->images as $image)

Your foreach loop in your view should loop through all the news models, but remember that each news model has multiple images, so you should have another loop inside your existing loop to display the images, i.e. foreach ($new->images as $image)

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

这篇关于Laravel Eloquent:belongsTo关系-错误:试图获取非对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆