一对多关系的控制器

时间:2017-12-31 10:52:47

标签: laravel eloquent laravel-5.2 one-to-many laravel-blade

我正在使用Laravel 5.2。

我有3个表(写作者,出版商和类别)所有一对多关系,表格名为图书

我不确定问题是什么,但每次我从我的视图刀片中调用其中2个(来自publishers表的nama_penerbit和来自categories表的nama_kategori)的列时,它会抛出一个错误 < em>尝试获取非对象的属性

这是我的模特

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

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 会抛出错误,而另一个效果很好

任何消化?

1 个答案:

答案 0 :(得分:3)

您正在为所有三种关系使用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');
}