[英]Laravel. Property does not exist on this collection instance. Relation error
我嘗試在我的數據庫中的不同表之間創建關系並從這些表中獲取數據,但出現錯誤:此集合實例上不存在屬性。
這是我的代碼:
遷移文件:
Schema::table('books', function (Blueprint $table) {
$table->foreignId('author_id')->constrained('authors')->onUpdate('cascade')->onDelete('cascade');
});
在模型\作者中:
public function books () {
return $this->hasMany('App\Models\Books');
}
在模型\書籍中:
public function author() {
return $this->belongsTo('App\Models\Authors');
}
在作者控制器中:
public function index () {
$authors = Authors::all();
return dd($authors->books);
}
在圖書控制器中:
public function index () {
$books = Books::all();
return dd($books->author);
}
如果有人知道如何解決這個問題,我將不勝感激。
你的模型是正確的,但當你調用 $authors->books 時你錯了,因為 $authors 是你的作者 model 的集合,而不是作者的 object。 如果你想檢查你的關系,你可以用這個例子來做:
public function index () {
$authors = Authors::latest()->first();;
dd($authors->books);
}
如果你想讓所有作者都擁有他們的書,請使用預先加載with()
public function index () {
$authors = Authors::with('books')->get();
return dd($authors);
}
如果你想要所有的書和他們各自的作者
public function index () {
$books = Books::with('author')->get();
return dd($books);
}
當您迭代刀片中的集合(如數組)時,您可以訪問關系
@foreach($books as $book)
<span>{{$book->author->name}}</span>
@endforeach
如果你只想得到一位作者的書,你可以這樣做
public function index () {
$authors = Authors::all();
// $authors is a collection of models (think of it as an advanced array)
// To get one of the models, you can iterate them with a loop or, for example, take the first one with "->first()"
//$authors->first() is an instance of the model "Author" class
return dd($authors->first()->books);
// $authors->first()->books is now a collection of models of "Book" class
}
您在作者和書籍之間的關系是一對多的,因此作者有許多書籍(就像您在hasMany
關系中正確陳述的那樣)。
這個 output 是一個集合,所以你不能那樣訪問它,而是需要像這樣循環它:
public function index () {
$authors = Authors::all();
$authors->books->each(function ($book) {
print_r($book);
}
}
如果您想檢索單個作者的書籍,您可以為作者返回單個 model 實例,例如:
public function index () {
$author = Authors::where('id',1)->first();
print_r($author->books);
}
謝謝你們,就我而言:正確的解決方案是:
在 model:
public function author() { return $this->belongsTo('App\Models\Authors', 'author_id'); }
在 controller 中:
$books = Books::with('author')->get();
在我添加的視圖文件中:
@foreach
<li>{{ $book->title}}</li>
<li>{{ $book->author->name}}</li>
@endforeach
再次感謝你。 該主題可以關閉))))))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.