Model.php第2709行中的LogicException:关系方法必须返回一个类型为Illuminate \ Database \ Eloquent \ Relations \ Relation

时间:2017-11-11 18:35:48

标签: php laravel laravel-5 eloquent

我应该在bookformat方法中显示作者详细信息。但面对LogicException。任何建议都要提前感谢。我在Model.php第2709行中遇到类似LogicException的错误:关系方法必须返回一个类型为Illuminate \ Database \ Eloquent \ Relations \ Relation的对象。任何帮助对我来说都很棒。如果我在bookFormat()中评论作者,一切正常。但Idk为什么我无法在bookformat()中获取作者详细信息。

#booksController.php
    namespace App\Http\Controllers;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Input;
    use App\Models\Book;
    use App\Models\Author;

    class BooksController extends Controller
    {
        public function index()
        {
            $books = Book::all();
            $results = [];
            foreach ($books as $book) {
             $results [] = $this->bookFormat($book);
         } 
         return $results; 
     }
        public function bookFormat($book){  
            return [ 
                'Id' => $book->id,
                'Title' => $book->title,
                'Author' => [ 
                    'Id' => $book->author->id,
                    'First_name' => $book->author->first_name,
                    'Last_name' => $book->author->last_name
                ],
                'Price' => $book->price,
                'ISBN' => $book->isbn,
                'Language' => $book->language,
                'Year' => $book->year_of_publisher
            ];
        }
    }

    //book.php
    namespace App\Models;
    use Illuminate\Database\Eloquent\Model;

    class Book extends Model
    {
        public $timestamps = TRUE;
        protected $table = 'books';
    //rules
        public static $rules = [
            'title' => 'required|max:255',
            'isbn' => 'required|max:50',
            'author_id' => 'required|max:255',
            'language' => 'required|max:255',
            'price' => 'required|max:255',
            'year_of_publisher' => 'required'
        ];
    //relationship
        public function author() {
            $this->belongsTo(Author::class);
        }
    }

1 个答案:

答案 0 :(得分:0)

而不是:

public function author() {
    $this->belongsTo(Author::class);
}

你应该:

public function author() {
    return $this->belongsTo(Author::class);
}

注意return差异。