【问题标题】:Laravel join three tables with relationshipsLaravel 用关系连接三个表
【发布时间】:2021-07-23 15:15:44
【问题描述】:

如何连接三个表,其中每个表的外部 ID 都是另一个表的一部分,

在下面的代码中,我试图从具有invoice_idPaymentsTable 和具有customer_idInvoiceTables 获取所有付款,

这是数据库关系

表:客户

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


【解决方案1】:

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

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

$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)
    }

【讨论】:

    【解决方案2】:

    由于您尚未定义关系,我们必须使用查询生成器,更新您的连接如下

     $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子句。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-15
      • 2021-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-27
      • 1970-01-01
      相关资源
      最近更新 更多