【发布时间】:2020-06-07 06:28:16
【问题描述】:
无法将所有书名和作者姓名显示为列表。得到错误。如果我在控制器(索引方法)中返回书籍和作者变量,我将数据作为数组。但无法在视图中访问它们。同样如下面的注释代码(在 Book Controller 中)所述,来自 laravel 文档的代码显示错误。
图书模型
class Book extends Model
{
protected $guarded = [];
public function authors(){
return $this->belongsToMany('App\Models\Author')->withTimestamps();
}
}
作者模型
class Author extends Model
{
public $guarded = [];
public function books(){
return $this->belongsToMany('App\Models\Book')->withTimestamps();
}
}
图书控制器
public function index()
{
$query = Book::with('authors')->get();
Pls Read the commented lines below -
//foreach ($query as $book) {
//return $book->authors->author_name; //Error: Property [author_name] does not exist on this collection instance.
//}
// (above code is given in laravel documentation but shows error : why?)
foreach($query as $b){
$books[] = $b->book_name;
$authors[] = $b->authors->first()->author_name;
}
return view('books.index', compact('books','authors'));
}
public function create()
{
return view('books.create');
}
public function store(validateAuthorBook $request)
{
$validated = $request->validated();
if($validated){
$book = new Book();
$book->book_name = $request->book_name;
$book->save();
$author = new Author();
$author->author_name = $request->author_name;
$author->save();
$book->authors()->attach($author);
}
return back()->with('status', 'Insert Successful!');
}
查看(index.blade.php)
@foreach($books as $b)
<tr>
<th>{{$loop->iteration}}</th>
<td>{{$b->book_name}}</td>
//<td>how to get author name</td>
@endforeach
</tr>
错误
Facade\Ignition\Exceptions\ViewException
Trying to get property 'book_name' of non-object (View:
D:\ProgrammingSSD\laragon\www\ulclibrary\resources\views\books\index.blade.php)
【问题讨论】:
标签: laravel many-to-many