【问题标题】:Add a key value pair to results from Laravel Model with pagination使用分页向 Laravel 模型的结果添加键值对
【发布时间】:2017-06-24 08:36:45
【问题描述】:

在我的控制器中,我正在调用我的发票模型,该模型正在执行分页选择。在我得到结果之后,我需要遍历每个结果并将 key => value 对添加到原始结果中。 我在 config/database.php 中设置了我的 laravel 以将结果作为数组获取:

'fetch' => PDO::FETCH_ASSOC,

我的控制器中的代码是

    $invoices = Invoices::getInvoices($clientId);
    $total = 0;
    foreach($invoices as $key=>$inv) {

        $payments = Payments::getPaymentAmount($inv['InvoiceId']);

        foreach($payments as $pmt) {

                $total += $pmt['Pmt_Amount'];

        }

        $invoices[$key]['total'] = $total;
    }

我的发票模型是:

public static function getInvoices($clientId)
{
   $invoices = DB::table('invoices')
    ->where('ClientId', '=', $clientId)
    ->paginate(25);
   return $invoices;
}

和我的付款模式

public static function getPaymentAmount($invoiceId)
{
    $payment = DB::table('payments')
        ->select('Pmt_Amount', 'PaymentStatusId')
        ->where('InvoiceId', $invoiceId)
        ->get();

    return $payment;
}

当我尝试将“总计”添加到发票数组时,我收到以下错误

间接修改Illuminate\Pagination\LengthAwarePaginator的重载元素无效

【问题讨论】:

  • 为什么在 Eloquent 模型中使用DB 来调用模型应该负责的表?

标签: php arrays laravel laravel-5.3 laravel-eloquent


【解决方案1】:

你的 $invoices 是对象,在你的 getInvoices() 函数之后尝试 toArray() :

$invoices = $invoices->toArray();

【讨论】:

  • 这行得通,但现在我的数据是完整的数组 - 在我添加了我需要的值之后,有没有办法将它转换回 Illuminate\Pagination\LengthAwarePaginator 对象格式,以便我的刀片模板可以作为以前?
猜你喜欢
  • 2020-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-22
  • 2016-01-29
  • 2021-06-30
  • 2020-07-19
  • 2014-12-26
相关资源
最近更新 更多