LogicException:关系方法必须返回 Illuminate\Database\Eloquent\Relations\Relation 类型的对象

问题描述 投票:0回答:1

我应该以书籍格式的方法显示作者详细信息。但面临LogicException。如有任何建议,请提前致谢。

我遇到这样的错误

LogicException in Model.php line 2709: Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation

任何帮助对我来说都是很大的。如果我在

bookFormat()
中评论作者,一切都会正常。但我不知道为什么我无法在我的 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);
        }
    }
php laravel laravel-5 eloquent
1个回答
1
投票

代替:

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

你应该:

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

注意

return
的区别。

© www.soinside.com 2019 - 2024. All rights reserved.