Laravel 连接三个具有关系的表

Laravel join three tables with relationships

如何加入三个 table,其中每个 table 的外部 ID 都是另一个的一部分,

在下面的代码中,我试图从 PaymentsTable 获得所有付款,其中 invoice_idInvoiceTables customer_id

这是数据库关系

Table:客户

customer_id; Primary Key

Table:发票

invoice_id: Primary key
customer_id: Foreign Key, Customers

Table:付款

payment_id: Primary Key
invoice_id: Foreign Key, Payments
        $payments = SalesPayments::where('payment_amount', '!=' , NULL)
            ->join('sales_invoices', 'sales_invoices.invoice_id', '=', 'sales_payments.invoice_id')
            ->join('payment_options', 'payment_options.paymentoption_id', '=', 'sales_payments.paymentoption_id')
            //->join('customers', 'customers.customer_id', '=', 'sales_payments.invoice_id')
            ->get();

以下关系已在支付模型中尝试过,

    public function customers()
    {   

        return $this->hasManyThrough(Customers::class, SalesInvoices::class, 'payment_id' ,'invoice_id', 'payment_id', 'customer_id' );

    }

现在对于每个付款行,我也想获取客户信息,那么如何获取呢?

假设您需要所有付款信息以及与该付款相关的发票和客户详细信息。

如果您正在寻找上述响应,那么您可以使用嵌套预加载简单地检索数据 喜欢

$payments=SalesPayments::with('salesInvoice.customer')->where(Your condition)->get();

在支付模式中

 public function SalesInvoice(){
  return $this->BelongsTo(Your sales model class)
}

在销售发票模型中

 public function customer(){
      return $this->BelongsTo(Your user model class)
    }

由于您尚未定义关系,我们必须使用查询构建器,按如下方式更新您的连接

 $payments = DB::table('sales_payments')
    ->join('sales_invoices', 'sales_invoices.invoice_id', '=', 'sales_payments.invoice_id')
    ->join('customers', 'sales_invoices.customer_id', '=', 'customers.customer_id')
    ->join('payment_options', 'payment_options.paymentoption_id', '=', 'sales_payments.paymentoption_id')
    ->select('sales_payments.*', 'sales_invoices.*', 'customers.*', 'payment_options.*')
    ->get();

然后你可以添加where子句。