渴望加载外表导致null

时间:2015-11-04 10:14:41

标签: php mysql laravel laravel-5

我有一对多的关系(类别有很多项目)我想加载。不幸的是,这导致NULL。 我是Laravel的新手,在阅读完文档之后,我不确定我做错了什么。

我希望在正确的方向上轻推,如果需要,我也可以发布迁移。

DD($项目)

Collection {#179 ▼
  #items: array:2 [▼
    0 => Item {#176 ▼
      #fillable: array:4 [▶]
      #connection: null
      #table: null
      #primaryKey: "id"
      #perPage: 15
      +incrementing: true
      +timestamps: true
      #attributes: array:8 [▶]
      #original: array:8 [▶]
      #relations: array:1 [▼
        "category" => null      <---- HERE --------<
      ]
      #hidden: []
      #visible: []
      #appends: []
      #guarded: array:1 [▶]
      #dates: []
      #dateFormat: null
      #casts: []
      #touches: []
      #observables: []
      #with: []
      #morphClass: null
      +exists: true
      +wasRecentlyCreated: false
    }
    1 => Item {#177 ▶}
  ]
}

上述ItemsController

public function index() {
   $items = Item::with('category')->get();

   return View::make('items.index')
   ->with('items', $items);
}

项目模型

class Item extends Model {
    protected $fillable = array('name', 'description', 'purchased_at', 'price');
    ...
    public function category() {
        return $this->belongsTo('App\Category');
    }
}

类别模型

class Category extends Model {
    protected $fillable = array('name');
    ...

    public function items() {
      return $this->hasMany('App\Item');
    }
}

1 个答案:

答案 0 :(得分:1)

该项目没有category_id。它也可以从可填充数组中丢失,因此在创建它时可能不会被设置。