复杂的数组在Laravel中表现出色

时间:2016-05-30 13:39:51

标签: php laravel-5.1

我有两个表,我想加入并创建一个Excel。

event_invoice

id
name
invoice_value
invoice_date

invoice 型号

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Invoice extends Model
{
    //
     protected $table = 'event_invoice';
     protected $primaryKey = 'Id';

    /*
     * An invoice can has many payments 
     *
     */

    public function duedates(){
        return $this->hasMany('App\invoiceduedates');
    }

}

INVOICEDUEDATE

id
invoice_id
date
amountin

duedatemodel

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class invoiceduedates extends Model
{
     protected $table = 'invoiceduedates';


}

因此,一张发票可以有很多专利

我希望以这种格式显示excel

| name | invoice_value | invoice_date | due date1  | due amount1 | due date2  | due amount2 | due date3  | due amount3 |
|------|---------------|--------------|------------|-------------|------------|-------------|------------|-------------|
| A    | 5000          | 30-01-2016   | 15-01-2016 | 2500        | 30-01-2016 | 04-11-1906  | null       | null        |
| B    | 8000          | 02-05-2016   | 15-02-2016 | 8000        | null       | null        | null       | null        |
| C    | 10000         | 03-05-2016   | 15-05-2016 | 5000        | 19-05-2016 | 2500        | 19-05-2016 | 2500        |

任何帮助将不胜感激

谢谢

1 个答案:

答案 0 :(得分:0)

问题与Laravel本身无关。

您要做的是使用允许您操作excel文件的库,例如PHPExcel,您可以使用Composer将其添加到Laravel项目中。

从现在开始,您只需收集数据并将其写入excel文件中:

$invoices = Invoice::with('duedates')->get();

foreach ($invoices as $invoice)
{
    // ... Write the basic fields such as "name" or "invoice_value"

    $dueDateCount = 0;
    foreach ($invoice->duedates as $dueDate)
    {
        // ... Write the specific invoice dates using $dueDateCount to specify the ID

        $dueDateCount++;
    }
}