Laravel有很多层次

时间:2014-09-23 11:36:25

标签: php laravel eloquent

我有一个非常具体的查询,我不知道如何进入Eloquent

我有以下表格

OrdersOrderInvoiceOrderPayment

因此,每个Order都有多个OrderInvoices,每个OrderInvoice都有很多OrderPayments

然后我有turns表,其中包含多笔付款

所以我想要的是获得与特定回合相关的所有订单

我知道如何获得所有发票:

$this->belongsToMany('OrderInvoice','orders_payments','turn_id','invoice_id');

但我需要下一级并获得订单, 我怎样才能在雄辩中实现这一目标?

非常感谢你!

编辑:表格结构

订单
id

OrderInvoice
ID
order_id

OrderPayment
ID
INVOICE_ID
turn_id

打开
ID

1 个答案:

答案 0 :(得分:2)

最直截了当:

// load related collections
$turn->load('invoices.orders');

// then
$turn->invoices; // collection of invoices, for each you can do this:
$turn->invoices->first()->orders; // collection of orders for an invoice

如果你想获得给定turn的单个订单集合,那么你需要这个技巧,这是最简单的方法(没有连接等),但在性能方面肯定不是最好的:

// store orders in a separate variable
$turn->load(['invoices.orders' => function ($q) use (&$orders) {
   $orders = $q->get()->unique();
}]);


// then
$orders; // single collection of all the orders related to the given turn

// also still accessible as usually:
$orders->invoices;
$orders->invoices->first()->orders;