使用Laravel 4和Eloquent查询相关模型 [英] Querying on related models using Laravel 4 and Eloquent

查看:61
本文介绍了使用Laravel 4和Eloquent查询相关模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Laravel 4,我有以下模型和关系:具有多条记录的事件具有多条记录.我想做的就是这样

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

原因是无效的,因为Eloquent在检索记录时不会将模型联接在一起.因此,如何在不自己编写SQL的情况下进行此操作(我想避免使用分页,但要避免这种情况).

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).

推荐答案

您想要的是急切加载.

如果要指定其他约束,它的工作原理如下:

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

这篇关于使用Laravel 4和Eloquent查询相关模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆