Я создаю систему обзора с Laravel. У меня есть таблица с именем
Таблица книг
Таблица пользователей
Таблица отзывов
В моей таблице отзывов у меня есть
$table->bigIncrements('id');
$table->unsignedInteger('user_id');
$table->unsignedInteger('book_id')->nullable();;
$table->string('headline')->nullable();
$table->text('description')->nullable();
$table->string('rating')->nullable();
$table->tinyInteger('approved')->nullable();
$table->timestamps();
В нем хранятся User_Id и Book_id
В моей BookReview
модели у меня есть эта
public function books()
{
return $this->belongsTo(Book::class);
}
public function users()
{
return $this->hasMany(User::class);
}
В user
модель
public function books()
{
return $this->belongsToMany(Book::class);
}
public function review()
{
return $this->hasOne(BookReview::class);
}
In Book
модель
public function reviews()
{
return $this->hasMany(BookReview::class);
}
В моем контроллере у меня есть
public function show(Book $book, Author $author_id) {
$data = array();
$data['relatedBooks'] = Book::where('author_id', $book->author_id)
->where('id', '!=', $book->id)
->take(5)->get();
$data['avg'] = BookReview::where('book_id', $book->id)->avg('rating');
$data['reviews'] = BookReview::where('book_id', $book->id)->get();
return view('book', compact("data"))->with('book', $book);
}
В моем блейде. php
@foreach($data['reviews'] as $review)
<p>{{ $review->user_id->name }}</p>
@endforeach
Но он вернул ошибку
Попытка получить свойство 'name' не-объекта (Представление: C: \ xampp1 \ newlibri \ resources \ views \ book.blade. php)
Я не знаю, что я делаю неправильно.
ОБНОВЛЕНИЕ
Книжный стол
public function up()
{
Schema::create('books', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->text('about');
$table->string('image_url');
$table->string('epub_url');
$table->integer('author_id');
$table->string('publisher');
$table->year('year');
$table->boolean('recommended')->default(0);
$table->timestamps();
});
}
ТАБЛИЦА ПОЛЬЗОВАТЕЛЯ
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('avatar')->nullable();
$table->string('password')->nullable();
$table->rememberToken();
$table->timestamps();
});
}
СТОЛ ОБЗОР
Schema::create('book_reviews', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedInteger('user_id');
$table->unsignedInteger('book_id')->nullable();;
$table->string('headline')->nullable();
$table->text('description')->nullable();
$table->string('rating')->nullable();
$table->tinyInteger('approved')->nullable();
$table->timestamps();
});
}