Laravel在获取数据时尝试获取非对象的属性

时间:2015-12-18 18:36:08

标签: laravel

当我获得部分数据和部分结果部分的问题时,我收到此错误 书中的部分和作者部分运作良好 当我删除部分部分时,它使用out_name Laravel Framework版本5.1.25(LTS)

Trying to get property of non-object (View: C:\xampp\htdocs\lib\resources\views\libraryViewsContainer\summary.blade.php)

my Book Model

class Book extends Model
{
    public function section()
    {
        return $this->belongsTo('App\Section','id');
    }

    public function author()
    {
        return $this->belongsToMany('App\Author','books_authors_relationship','book_id','author_id')->withTimestamps();
    }

my BooksController

public function summary(){
        $all_results = Book::with('section')->with('author')->get();
        return view('libraryViewsContainer.summary',compact('all_results',$all_results));
    }

我的摘要刀片

    <div class="container">
        <h1 class="well text-center">Library Summary</h1>
        <table class="table">
            <tr>
                <th style="width: 25%">Section Name</th>
                <th style="width: 25%">Book Title</th>
                <th style="width: 25%">Book Description</th>
                <th style="width: 25%">Authors</th>
            </tr>

            @foreach($all_results as $bookModel)
                <tr>
                    <td>
                        <a href="/section/{{$bookModel->section->id}}">
                        <span class="label label-info">{{$bookModel->section->section_name}}</span>
                        </a>
                    </td>
                    <td>
                        {{$bookModel->book_title}}
                    </td>
                    <td>
                        {{$bookModel->book_description}}
                    </td>
                    <?php $authors = $bookModel->author; ?>
                    <td>
                        @foreach($authors as $author)
                            <a href="/author/{{$author->id}}">
                                <span class="label label-danger">{{$author->first_name}} {{$author->last_name}}</span>
                            </a>
                        @endforeach
                    </td>
                </tr>
            @endforeach
        </table>
    </div>
@stop

2 个答案:

答案 0 :(得分:1)

错误发生在Book模型中 我改变了

public function section()
    {
        return $this->belongsTo('App\Section','id');
    }

return $this->belongsTo('App\Section');

感谢大家的帮助

答案 1 :(得分:0)

        
  1. 在控制器中,方法“with”可以写成 $ all_results = Book :: with('section','author') - &gt; get();
  2.     
  3. 方法compact()接受变量名称,而不是变量。     
  4. 在查看之前返回$ all_results以查看结果,以确定您是否正确获取值。