6

I'm using the eloquent ORM in Laravel with a hasMany relationship.

when I run:

Level::find(1)->lessons()->get();

It works fine, but when I use the dynamic property like so:

Level::find(1)->lessons

It just returns results for the level instead of the lessons.

Do I need another setting somewhere?

EDIT: Here are the models:

class Level extends Eloquent {

    protected $table = 'levels';

    public function lessons()
    {
        return $this->hasMany('Lesson');
    }
}

class Lesson extends Eloquent {

    protected $table = 'lessons';

    public function level()
    {
        return $this->belongsTo('Level');
    }
}
Rob
  • 10,851
  • 21
  • 69
  • 109
  • added the models, it's nothing special, just following the documentation, not sure if I'm missing some other param or setting to make it work. – Rob Sep 10 '13 at 16:40
  • That's bizarre, everything is correct. – wesside Sep 10 '13 at 19:26
  • Ya, I'm really not doing anything special here and the `get()` call works just fine. It returns no errors, nothing, it just doesn't run. If I echo out the last query it shows the query for fetching the `level` rather than the `lessons` for that level. – Rob Sep 11 '13 at 07:11
  • [This may help](http://stackoverflow.com/questions/18913560/laravel-4-how-to-access-reverse-one-to-many-relation/19015323#19015323). – The Alpha Sep 25 '13 at 22:40

2 Answers2

8

I just had the same problem, turns out I had a column on the table that had the same name as the relationship I set up.

Make sure you don't have a column in the model that has the same name as the relationsip method you are trying to load.

EDIT: I also noticed laravel has problems with undescores (_) in relationship names, so don't put an _ in the methodname or else it won't work.

Ezra
  • 1,388
  • 1
  • 13
  • 14
3

You need to eager load the relationship.

Level::with('lessons')->find(1)->lessons; should work.

If you want to load this relationship every time, you should add this line to Level model.

protected $with = array('lessons');

tharumax
  • 1,251
  • 9
  • 15