2015-07-03 105 views
0

我在我的应用程序中有三个数据库表。作为一个例子,这里是我现在有:在Laravel中有两个或多个外键的表格

items TABLE: id, quantity, price, month_id (FK), department_id (FK) 
months TABLE: id, month 
department TABLE: id, department 

我已经定义的模型hasManybelongsTo关系。通过这些关系,我可以执行查询App\Month::first()->items来检索所有第一个月的项目。但是,如果我想查询月份和部门,在这种情况下最好的方法是什么?

我当然可以就这样做:

$month = App\Month::first(); 
$month->items()->where('department_id', '3')->get(); 

是否有这样做的查询更优雅的方式?

+0

试试这个:' month :: with(['items'=> function($ q){$ q-> where('department_id',3)}]) - > first();' –

回答

0

首先,你可以告诉雄辩渴望加载需要的关系,以获得更好的性能。你可以通过使用和()方法来解决所有需要的关系 - 参见http://laravel.com/docs/5.0/eloquent#eager-loading了解更多细节。

而且,如果你想申请上加载关系中的一些附加条件,你可以这样做,使用相同的方法,但使用不同的语法来定义关系和标准:

$users = User::with(['posts' => function($query) 
{ 
    $query->where('title', 'like', '%first%'); 

}])->get();