我有一份书籍清单和作者名单。我建立了模型关系,以便我的书模型说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
我知道它应该正常工作,我只用书籍和作者重建它,它在那里工作得很好。
那么,有没有人有想法,我哪里出错?
谢谢,
乔治
答案 0 :(得分:2)
在您的Book
模型中,将authors
方法更改为author
,如下所示:
public function author()
{
return $this->belongsTo('Author');
}
因为,根据您的关系,一本书属于一位作者,当您致电authors
时,belongsTo->getResults()
被调用并运行错误的query
,因此authors
获取null你得到错误。要记住的事情:
hasOne
和belongsTo
关系,请使用单一形式的关系方法,即author
而不是authors
。 hasOne
或belongsTo
会返回单个模型对象。
对于hasMany
和belongsToMany
关系,请使用复数形式的关系方法,即authors
而非author
。
hasMany
和belongsToMany
返回一组模型对象。