【发布时间】:2014-05-26 17:57:12
【问题描述】:
我有一个书籍列表和一个作者列表。我建立了模型关系,所以我的书模型说books->belongTo('Author'),我的作者模型说authors->hasMany('Book')。
所以通常我可以通过以下方式访问 a 变量: $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');
}
}
作者.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
我知道它应该正常工作,我只用书籍和作者重建它,它在那里工作正常。
那么,有人知道我哪里出错了吗?
谢谢,
乔治
【问题讨论】:
-
有没有作者没有书的?如果你这样做了,你提到的错误就会被触发。
-
不知道是什么问题,但现在已经解决了。我只是将模型的方法更改为单数,现在它可以工作了。很奇怪。
标签: php laravel laravel-4 eloquent