【问题标题】:Get only last updated row of joined table in Laravel仅获取 Laravel 中连接表的最后更新行
【发布时间】:2021-07-18 09:48:03
【问题描述】:

我有以下代码用于从数据库中获取数据,

        $invoices = SalesInvoices::where('is_invoice', 1)
        ->join('customers', 'customers.customer_id', '=', 'sales_invoices.customer_id')
        ->join('sales_payments', 'sales_payments.invoice_id', '=', 'sales_invoices.invoice_id')
        ->orderBy("sales_payments.created_at", "desc") //Get the latest updated payment for view in table for just 1 row.
        ->get();

Sales_payments 表具有不同的付款阶段,其中包含多个条目,例如 Received、Partial、Completed 等,每个阶段数据行都有invoice_id,这是SalesInvoices 的主键。

现在我在DataTables 中显示所有发票,但是使用上面的代码,我得到sales_payments 的所有值,但我只需要最后更新的条目,它具有最新的created_at

如何在Sales_payments中只获得一个发票行但最新的付款状态,

谢谢,

【问题讨论】:

    标签: sql laravel eloquent


    【解决方案1】:

    有多种选择: 一种。这是因为您已经在 desc 订购了 salespayment.created,因此获得第一个

    $invoices = SalesInvoices::where('is_invoice', 1)
            ->join('customers', 'customers.customer_id', '=', 'sales_invoices.customer_id')
            ->join('sales_payments', 'sales_payments.invoice_id', '=', 'sales_invoices.invoice_id')
            ->orderBy("sales_payments.created_at", "desc") //Get the latest updated payment for view in table for just 1 row.
            ->first();
    

    b.使用最新

    $invoices = SalesInvoices::where('is_invoice', 1)
                ->join('customers', 'customers.customer_id', '=', 'sales_invoices.customer_id')
                ->join('sales_payments', 'sales_payments.invoice_id', '=', 'sales_invoices.invoice_id')
                ->latest('sales_payments.created_at')->first();
    

    c。最后

    $invoices = SalesInvoices::where('is_invoice', 1)
                ->join('customers', 'customers.customer_id', '=', 'sales_invoices.customer_id')
                ->join('sales_payments', 'sales_payments.invoice_id', '=', 'sales_invoices.invoice_id')
                ->last();
    

    【讨论】:

    • 如果SalesInvoices中有10张发票,这将导致仅输出1张发票
    • 对不起,你想达到什么目的?我的意思是你希望的输出是什么?
    • 我想查看所有发票,但 sales_payment 状态应该是sales_payments coumn 中的最新状态。
    • 那么你可以执行2个查询。第一个查询获取最新的销售付款状态,然后从第一个查询中查询 sales_payment 变量的所有发票。
    猜你喜欢
    • 2021-10-03
    • 2016-05-31
    • 1970-01-01
    • 2014-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-09
    • 2018-07-14
    相关资源
    最近更新 更多