Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying on related models using Laravel 4 and Eloquent

Using Laravel 4 I have the following models and relations: Event which hasMany Record which hasMany Item. What I would like to do is something like this

Item::where('events.event_type_id', 2)->paginate(50);

This of cause doesn't work as Eloquent doesn't JOIN the models together when retrieving the records. So how do I go about this without just writing the SQL myself (which I would like to avoid as I want to use pagination).

like image 929
Kanten Avatar asked Dec 05 '25 14:12

Kanten


1 Answers

What you want is eager loading.

It works like this if you want to specify additional constraints:

Item::with(array('events' => function($query) {
    return $query->where('event_type_id', 2);
}))->paginate(50);
like image 153
Franz Avatar answered Dec 08 '25 02:12

Franz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!