Не удалось получить значение реляционной модели в веб-сайте maatwebsite - PullRequest
0 голосов
/ 23 сентября 2018

Работа этой функции заключается в создании отчета о конкретном состоянии.Таким образом, я создаю отчет с двумя таблицами (Пользователь и Бронирование), с первичным ключом является ИД пользователя и резервирование.Оба столика будут забиты отношениями.Теперь я хочу создать Excel с использованием пакета maatwebsite в этом состоянии.От (таблица бронирования) и до (таблица бронирования) с ticketstatus (таблица бронирования), а также с типом пользователя (из пользовательского).Например, с 01.09.2018 по 23.09.2018 со статусом заявки как «забронировано» и типом пользователя как «Обычный или агент».Но я получаю сообщение об ошибке. Я использую метод FromQuery на веб-сайте maatwebsite для выполнения этой функции.

Я добавляю все коды здесь, модель пользователя:

<?php

namespace App;
use App\Booking;
use App\Wallet;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $primaryKey = 'userid';

    protected $fillable = ['name', 'phone', 'email','password','usertype'];

    protected $dates = [
        'createdAt'
    ];

    const CREATED_AT = 'createdAt';
    const UPDATED_AT = 'updatedAt';

    public function bookings()
    {
        return $this->hasMany('App\Booking', 'userid');
    }

    public function walletUsers()
    {
        return $this->hasOne('App\Wallet', 'userid');
    }

    public function supports()
    {
        return $this->hasMany('App\Help', 'userid');
    }

    public function getNameAttribute($value)
    {
        return ucfirst($value);
    }
}

Модель бронирования:

<?php

namespace App;
use Carbon\Carbon;

use Illuminate\Database\Eloquent\Model;

class Booking extends Model
{
    protected $primaryKey = 'bookingid';

    protected $dates = [
        'createdAt','updatedAt'
    ];

    const CREATED_AT = 'createdAt';
    const UPDATED_AT = 'updatedAt';

    public function users()
    {
        return $this->belongsTo('App\User', 'userid');
    }

    public function getDateOfIssueAttribute($value) {

        return Carbon::parse($value)->format('d-M-Y , h:m a');
    }

    public function getDateOfCancellationAttribute($value) {

        return Carbon::parse($value)->format('d-M-Y , h:m a');
    }

    public function getDojAttribute($value) {

        return Carbon::parse($value)->format('d-M-Y , h:m a');
    }
}

Теперь контроллер:

public function report(Request $request){
    $from = $request->from;
    $to = $request->to;
    $bookingtype = $request->bookingtype;
    $usertype = $request->usertype;

    return (new BookingsExport($from, $to, $bookingtype, $usertype))->download('invoices.xlsx');
}

Маршрут:

Route::post('/admin/reports/collect',[
    'uses' => 'ReportController@report',
    'as' => 'reports.generate'
]);

Maatwebsite Класс:

<?php

namespace App\Exports;

use App\Booking;
use App\User;
use Carbon\Carbon;
use App\Http\Controllers\ReportController;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithStrictNullComparison;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use Maatwebsite\Excel\Concerns\WithColumnFormatting;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use Maatwebsite\Excel\Concerns\WithMapping;


class BookingsExport implements FromQuery, WithStrictNullComparison, WithHeadings, ShouldAutoSize, WithColumnFormatting, WithMapping {
    use Exportable;

    public function __construct($from, $to, $bookingtype, $usertype)
    {
        $this->from = $from;
        $this->to = $to;
        $this->bookingtype = $bookingtype;
        $this->usertype = $usertype;
    }

    public function headings(): array
    {
        return [

            'Booking Id',
            'Block Key',
            'Bus Type',
            'DOJ',
            'status',
            'Created At',
            'Updated At',
            'Usertype',
            'Name'
        ];
    }

    public function map($booking): array
    {
        return [
            $booking->bookingid,
            $booking->blockkey,
            $booking->busType,
            $booking->doj,
            $booking->status,
            $booking->createdAt,
            $booking->updatedAt,
            $booking->users->usertype,
            $booking->users->name
        ];
    }


    public function columnFormats(): array
    {
        return [
            'D' => 'dd-mm-yyy',
            'E' => NumberFormat::FORMAT_DATE_DDMMYYYY
        ];
    }


    public function query()
    {
        $from = $this->from;
        $to = $this->to;
        $bookingtype = $this->bookingtype;
        $usertype = $this->usertype;

        if(isset($from) && isset($to) && is_null($bookingtype) && is_null($usertype))
        {
            return Booking::query()->whereBetween('createdAt',[$from, $to]);   
        }


        if(isset($from) && isset($to) && isset($bookingtype) && is_null($usertype))
        {
            return Booking::query()->whereBetween('createdAt',[$from, $to])->where('status','=', $bookingtype);
        }


        if(isset($from) && isset($to) && isset($bookingtype) && isset($usertype))
        {
            return Booking::query()->with('users')->whereHas("users", function($subQuery){ 
                $subQuery->where("usertype", "=", $usertype);})->whereBetween('createdAt',[$from, $to])->where('status','=', $bookingtype);
        }
    }
}

Ошибка, которую я получаю: «Не определено»variable: usertype "из последнего запроса файла класса Maatwebsite.Но я сею все значения от контроллера к этому, я даже dd ($ usertype), но я получаю значение как агент, но он показывает ошибку при использовании в нем запроса!Пожалуйста, руководство

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...