如何通过关系模型显示数据库中的变量?

时间:2014-04-12 14:48:46

标签: php laravel laravel-4 eloquent

我有一份书籍清单和作者名单。我建立了模型关系,以便我的书模型说books->belongTo('Author')和我的作者模型说authors->hasMany('Book')

通常我可以通过以下方式访问变量: $ books = Book :: all();

然后在视图中:

@foreach($books as $book)           
        <div>{{$book->id}}</div>
        <div>{{$book->title}}</div>
        <div>{{$book->authors->firstname}}</div>            
@endforeach

但这不起作用。我收到错误消息:尝试获取非对象的属性

所以这是我的文件:

我的模特:

book.php中

 class Book extends \Eloquent {
protected $guarded = [];

public function religions()
{
    return $this->belongsTo('Religion');
}

public function branches()
{
    return $this->belongsTo('Branch');
}

public function authors()
{
    return $this->belongsTo('Author');
}

public function quotes()
{
    return $this->hasMany('Quote');
}

public function chapters()
{
    return $this->hasMany('Chapter');
}
 }

Author.php

class Author extends \Eloquent {
    protected $guarded = [];

    public function books()
    {
        return $this->hasMany('Book');
    }

    public function quotes()
    {
        return $this->hasMany('Quote');
    }

    public function branches()
    {
        return $this->belongsTo('Branch');
    }

    public function religions()
    {
        return $this->belongsTo('Religion');
    }
}

然后来我的控制器:

ReligionBranchBookController

class ReligionBranchBookController extends \BaseController {

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index($religionId, $branchId)
    {
        //
        // $books = Book::where('religion_id', $religionId)->where('branch_id', $branchId)->get();
        $books = Book::all();
        $authors = Author::all();
        // dd($books->toArray());

        return View::make('books.index')
            ->with('religionId', $religionId)
            ->with('branchId', $branchId)
            ->with('books', $books)
            ->with('authors', $authors);
    }

}

我的观点:

index.blade.php

 @extends('layout.main')

@section('content')

    <h1>Books List!!</h1>

    <table>
        <tr>
            <th>ID</th>
            <th>Title</th>
            <th>Author</th>
        </tr>

        @foreach($books as $book)
            <tr>
                <td>{{$book->id}}</td>
                <td>{{$book->title}}</td>
                <td>{{$book->authors->firstname}}</td>
            </tr>
        @endforeach
    </table>

@stop

我知道它应该正常工作,我只用书籍和作者重建它,它在那里工作得很好。

那么,有没有人有想法,我哪里出错?

谢谢,

乔治

1 个答案:

答案 0 :(得分:2)

在您的Book模型中,将authors方法更改为author,如下所示:

public function author()
{
    return $this->belongsTo('Author');
}

因为,根据您的关系,一本书属于一位作者,当您致电authors时,belongsTo->getResults()被调用并运行错误的query,因此authors获取null你得到错误。要记住的事情:

  • 对于hasOnebelongsTo关系,请使用单一形式的关系方法,即author而不是authors
  • hasOnebelongsTo会返回单个模型对象。

  • 对于hasManybelongsToMany关系,请使用复数形式的关系方法,即authors而非author

  • hasManybelongsToMany返回一组模型对象。