【问题标题】:Laravel Has Many Trough with multiple levelsLaravel 有许多多层次的低谷
【发布时间】:2014-11-17 14:25:18
【问题描述】:

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

我有以下表格

Orders,OrderInvoice,OrderPayment

所以每个Order 有很多OrderInvoices,每个OrderInvoice 有很多OrderPayments

然后我有一张桌子turns 有很多付款

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

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

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

但我需要下一个级别并获得订单, 我怎样才能在 eloquent 中做到这一点?

非常感谢!

编辑:表格结构

订单
身份证

订单发票
身份证
order_id

订单支付
身份证
invoice_id
turn_id

转弯
身份证

【问题讨论】:

  • 显示您的表格,因为您的描述不清楚 - turn 与 OrderInvoice 有什么关系,为什么它在 orders_payments 数据透视表中?如果是hasMany,那么根本就没有数据透视表..
  • 刚刚用表格及其相关字段编辑了问题

标签: php laravel eloquent


【解决方案1】:

最直接的:

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

【讨论】:

  • 我终于用上了这个功能,有没有更好的方法呢? (&$orders) 东西崩溃了... ``` public function orders(){ //GSTODO: 改进这个以获得更高的性能 $this->load('invoices.order'); $orders = $this->invoices()->first()->order; foreach($this->invoices() as $invoice){ $orders->merge($invoice->order); } 返回 $orders; } ```
  • crashed 是什么意思?
  • 使用此代码 pastebin.com/B67MkLc5 我得到一个语法错误,意外的 '(',期待 '{' 错误
  • 是的,关闭时缺少use。检查编辑。
  • 我明白了,它似乎可以工作:D 但是,当我尝试将 ->where() 添加到 $orders 时,我发现这是一个未定义的方法:D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-08
  • 2023-02-03
  • 2021-11-20
  • 2023-03-23
相关资源
最近更新 更多