我的应用程序中有三个数据库表。举个例子,这就是我现在所拥有的:
items TABLE: id, quantity, price, month_id (FK), department_id (FK)
months TABLE: id, month
department TABLE: id, department
我已经在模型上定义了hasMany
和belongsTo
关系。通过这些关系,我可以执行查询App\Month::first()->items
来检索所有第一个月的项目。但是,如果我想查询月份和部门,在这种情况下,最好的方法是什么?
我当然可以这样做:
$month = App\Month::first();
$month->items()->where('department_id', '3')->get();
有更优雅的方式来进行此查询吗?
答案 0 :(得分:0)
首先,您可以告诉Eloquent急切地加载所需的关系以获得更好的性能。您可以使用 with()方法并隐藏所有需要的关系来执行此操作 - 有关详细信息,请参阅http://laravel.com/docs/5.0/eloquent#eager-loading。
此外,如果要对加载的关系应用一些其他条件,可以使用相同的 with 方法,但使用不同的语法来定义关系和条件:
$users = User::with(['posts' => function($query)
{
$query->where('title', 'like', '%first%');
}])->get();