책 목록과 저자 목록이 있습니다. 나는 모델 관계를 만들어서 나의 책 모델이 그것을 말하고 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
나는 그것이 정상적으로 작동해야한다는 것을 알고 있고, 책과 작가로만 재구성하고 거기에서 잘 작동합니다.
그래서 누군가 내가 어디로 잘못 가고 있는지 아이디어가 있습니까?
감사,
성 조지
당신의에서 Book
모델 변경 authors
에 방법을 author
다음과 같습니다 :
public function author()
{
return $this->belongsTo('Author');
}
한 권의 책은 당신의 관계에 따라 한 저자에 소유하고 호출 할 때, 때문에 GET라는 잘못된 실행 그래서 GET 널을 당신은 오류가 발생합니다. 기억해야 할 사항 :authors
belongsTo->getResults()
query
authors
hasOne
와 belongsTo
관계 방법의 관계를 사용 단수형, 즉 author
없습니다 authors
.hasOne
또는 belongsTo
단일 모델 객체를 반환합니다.
들어 hasMany
와 belongsToMany
관계 방법의 관계를 사용 복수 형태, 즉 authors
없습니다 author
.
hasMany
와 belongsToMany
모델 개체의 컬렉션을 반환합니다.이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다