【问题标题】:Laravel Eloquent 'belongs to' relationship books and its categoryLaravel Eloquent“属于”关系书籍及其类别
【发布时间】:2015-03-22 17:52:52
【问题描述】:

我正在尝试打印“书籍”表中所有书籍的名称及其关联的类别。但它不显示任何内容或错误消息。

型号::Book.php

class Book extends Eloquent{
    protected $table ='books';

    public function bookCat()
    {
        return $this->belongsTo('BookCategory');
    }
}

型号::BookCategory.php

class BookCategory extends Eloquent{
    protected $table ='book_categories';

}

控制器::route.php

Route::get('/', function()
{
    $books = Book::all();

    return View::make('books')
    ->with('books', $books);
});

查看::books.blade.php

@foreach ($books as $book)

<li>{{ $book->book_name }}</li>
- <small>{{ $book->bookCat }}</small>

@endforeach

表::书

(int)id, (string)book_name, (int)category_id

表::book_categories

(int)id,(字符串)类别

【问题讨论】:

  • 确保数据库中的数据正确并尝试打印实际名称:{{ $book-&gt;bookCat-&gt;category }}

标签: php laravel-4 eloquent


【解决方案1】:

将关系添加到 BookCategory。

class BookCategory extends Eloquent{
    protected $table ='book_categories';

    public function books() {
        return $this->hasMany('Book');
    }
}

您的本地密钥也与模型名称不匹配,因此您需要在关系中指定:

class Book extends Eloquent{
    protected $table ='books';

    public function bookCat()
    {
        return $this->belongsTo('BookCategory', 'category_id');
    }
}

您可能还想在控制器中预先加载类别,因为您的查询是针对书籍的:

$books = Book::with('bookCat')->get();

【讨论】:

  • 它说 throw new \BadMethodCallException("Call to undefined method {$className}::{$method}()");
  • BadMethodCallException 调用未定义的方法 Illuminate\Database\Query\Builder::all()
  • 问题是急切加载方法。当我将其更改为 $books = Book::all();有用。但是如何解决急切加载问题呢?
  • 糟糕,我的错 - 应该是 Book::with('bookCat')-&gt;get();
  • 另一件事,在您的模板中,您实际上并没有呼应类别名称 - 更改为 {{ $book-&gt;bookCat-&gt;category }}
猜你喜欢
  • 2023-03-28
  • 2021-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-19
  • 2020-01-29
相关资源
最近更新 更多