【问题标题】:LogicException in Model.php line 2709: Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\RelationModel.php 第 2709 行中的 LogicException:关系方法必须返回 Illuminate\Database\Eloquent\Relations\Relation 类型的对象
【发布时间】:2018-04-24 18:50:54
【问题描述】:

我应该在 bookformat 方法中显示作者详细信息。但是面对LogicException。任何建议提前感谢。我在 Model.php 第 2709 行中遇到类似 LogicException 的错误:关系方法必须返回 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);
        }
    }

【问题讨论】:

  • 非常感谢@Marcin
  • 如果它解决了您的问题,请将答案标记为已接受
  • 你能解释一下我如何在逆关系中写这个吗?感谢您的建议
  • 在Author类中你可以写public function books() { return $this->hasMany(Book::class); }。您应该阅读 Eloquent 文档了解更多详细信息

标签: php laravel laravel-5 eloquent


【解决方案1】:

代替:

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

你应该有:

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

注意return 的区别。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-26
    • 2018-03-20
    • 2014-07-09
    • 2017-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多