Hướng dẫn fromquery laravel excel - fromquery laravel excel

Trong ví dụ trước, chúng tôi đã thực hiện truy vấn bên trong lớp xuất khẩu.Mặc dù đây là một giải pháp tốt cho xuất khẩu nhỏ, nhưng đối với xuất khẩu lớn hơn, điều này sẽ có giá hiệu suất khổng lồ.

Bằng cách sử dụng mối quan tâm FromQuery, chúng tôi có thể chuẩn bị một truy vấn cho xuất khẩu.Đằng sau hậu trường, truy vấn này được thực hiện trong các khối.

Trong lớp InvoicesExport, thêm mối quan tâm FromQuery và trả về truy vấn.Hãy chắc chắn không ->get() kết quả!not ->get() the results!

namespace App\Exports;

use App\Invoice;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\Exportable;

class InvoicesExport implements FromQuery
{
    use Exportable;

    public function query()
    {
        return Invoice::query();
    }
}

123456789101112131415
2
3
4
5
6
7
8
9
10
11
12
13
14
15

Chúng tôi vẫn có thể tải xuống xuất khẩu theo cùng một cách:

return (new InvoicesExport)->download('invoices.xlsx');

1

# Tùy chỉnh truy vấn

Thật dễ dàng để chuyển các tham số tùy chỉnh cho truy vấn, chỉ cần chuyển chúng dưới dạng phụ thuộc vào lớp xuất.

# Như tham số hàm tạo

namespace App\Exports;

use App\Invoice;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\Exportable;

class InvoicesExport implements FromQuery
{
    use Exportable;

    public function __construct(int $year)
    {
        $this->year = $year;
    }

    public function query()
    {
        return Invoice::query()->whereYear('created_at', $this->year);
    }
}

1234567891011121314151617181920
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

Năm nay, năm có thể được thông qua dưới dạng phụ thuộc vào lớp xuất khẩu:

return (new InvoicesExport(2018))->download('invoices.xlsx');

1

# Như setter

namespace App\Exports;

use App\Invoice;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\Exportable;

class InvoicesExport implements FromQuery
{
    use Exportable;

    public function forYear(int $year)
    {
        $this->year = $year;
        
        return $this;
    }

    public function query()
    {
        return Invoice::query()->whereYear('created_at', $this->year);
    }
}

12345678910111213141516171819202122
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

Chúng ta có thể điều chỉnh năm bằng cách sử dụng phương pháp

return (new InvoicesExport)->download('invoices.xlsx');
0:

return (new InvoicesExport)->forYear(2018)->download('invoices.xlsx');

1