【发布时间】:2018-06-11 00:44:39
【问题描述】:
我正在使用 Laravel 5.2。
我有 3 个表格(作家、出版商和类别),所有表格都是 一对多关系,表格名为 books。
我不太确定问题出在哪里,但每次我从视图刀片中调用其中 2 个列(publishers 表中的 nama_penerbit 和类别表中的 nama_kategori)时,都会向我抛出错误 试图获取非对象的属性
这是我的模型
Book.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Book extends Model
{
protected $fillable = [
'judul',
'label',
'isbn',
'tanggal_terbit',
'status',
'id_penulis',
'id_penerbit',
'id_kategori',
];
// Book with Writter
public function writter()
{
return $this->belongsTo('App\Writter', 'id_penulis');
}
// Book with Publisher
public function publisher()
{
return $this->belongsTo('App\Writter', 'id_penerbit');
}
// Book with Category
public function category()
{
return $this->belongsTo('App\Writter', 'id_kategori');
}
}
Publisher.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Publisher extends Model
{
protected $fillable = [
'nama_penerbit',
];
// Relation Book with Publisher
public function book() {
return $this->hasMany('App\Book', 'id_penerbit');
}
}
Writer.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Writter extends Model
{
protected $fillable = [
'nama_penulis',
];
// Relation Book with Writter
public function book() {
return $this->hasMany('App\Book', 'id_penulis');
}
}
Category.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $fillable = [
'nama_kategori',
];
// Relation Book with Category
public function book() {
return $this->hasMany('App\Book', 'id_kategori');
}
}
my-view.blade.php
<span>{{ $book->writter->nama_penulis }}</span> // works like a charm
<span>{{ $book->publisher->nama_penerbit }}</span> // throw me an error
<span>{{ $book->category->nama_kategori }}</span> // throw me an error
我的问题是为什么 nama_penerbit 和 nama_kategori 会抛出错误,而另一个运行良好
有什么建议吗?
【问题讨论】:
标签: laravel eloquent laravel-5.2 one-to-many laravel-blade