一对多关系的控制器

Controller For One To Many Relationships

我正在使用 Laravel 5.2。

我有 3 个 table(作家、出版商和类别)所有都是 一对多关系 与 table 命名为 书籍.

我不太确定问题出在哪里,但每次我从其中 2 个调用该列(nama_penerbit 来自出版商 table 和 nama_kategori 来自类别 table) 从我的观点来看,它抛出一个错误 Trying to get 属性 of non-object

这是我的模型

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');
    }
}

Writter.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');
    }
}

我的-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 抛出一个错误而另一个运行良好

有什么建议吗?

您正在为所有三种关系使用 Writter 模型,因此请通过设置正确的模型来修复这些关系:

// Book with Publisher
public function publisher()
{
    return $this->belongsTo('App\Publisher', 'id_penerbit');
}

// Book with Category
public function category()
{
    return $this->belongsTo('App\Category', 'id_kategori');
}