【发布时间】:2021-07-23 15:15:44
【问题描述】:
如何连接三个表,其中每个表的外部 ID 都是另一个表的一部分,
在下面的代码中,我试图从具有invoice_id 的PaymentsTable 和具有customer_id 的InvoiceTables 获取所有付款,
这是数据库关系
表:客户
customer_id; Primary Key
表格:发票
invoice_id: Primary key
customer_id: Foreign Key, Customers
表格:付款
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' );
}
现在,对于每个付款行,我也想获取客户信息,那么我该如何获取呢?
【问题讨论】:
-
请显示您的数据库关系架构,因为这将帮助我们找到正确的查询。
-
添加键约束
-
从你的问题来看,我觉得你可能不需要客户信息,如果是真的,你不需要加入客户表,如果你需要它,它更像是一个有-many-through 关系,但需要更清楚您的问题。回复会员时使用@,以便我们收到通知。
-
@PrafullaKumarSahu,我需要在付款视图中显示客户姓名,因此我必须需要客户信息。我尝试使用 hasManyThrough,但似乎在某个地方失败了,因为我必须与 Payments 一起加入 3 个表。
-
@rjcode 你只想选择与所有3个表都有关系的记录吗?
标签: php laravel join eloquent relationship