mercredi 4 novembre 2015

Eager loading foreign table results in null

I have a one to many relationship (Category has many Item) which I would like to eager load. Unfortunately this results in NULL. I am new to Laravel and after reading the documentation I am not sure what I am doing wrong.

I would appreciate a nudge in the right direction and if needed I can post the migrations too.

dd($items)

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

Item Model

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

Category Model

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

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



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire