Laravel - 通过变压器保持柱子的运行记录

时间:2015-12-15 17:52:17

标签: php laravel

所以我有一个Contribution模型。我有一个控制器可以提取所有贡献并将它们发送到变压器,如下所示:

我的控制器:

public function showContributions (Request $request, $memberId)
{
    $perPage = $request->input('per_page', 15);
    $contribution = parent::getRepo('Contribution');

    $contributions = Cache::tags(['contributions'])->remember("contributions.$memberId.2", 60, function() use ($perPage, $memberId, $contribution){
        return $contribution->where('vip_id', $memberId)->where('fund_id', 2)->paginate($perPage);
    });

    $transformedData = $this->fractal->paginatedCollection($contributions, new ContributionTransformer(), 'contributions');
    return $this->sendResponse($transformedData['contributions'], $transformedData['meta']);
}

我的变压器:

    public function transform(Contribution $contribution)
    {
        setlocale(LC_MONETARY, 'en_US.UTF-8'); // Set so that money_format uses the dollar sign instead of USD. Consider moving to bootstrap
        $report = $contribution->report;
        $employer = $report->employer;
        $employerHours = $contribution->employerHours;

        $contributionLocal = $contribution->local->local_code ?? '';
        $employerLocal = $employerHours->local->local_code ?? '';

        $reciprocalLocal = $contributionLocal === $employerLocal ? '0000' : $employerLocal;

        $response = [
            'id' => $contribution->member_hours_id,
            'report_number' => $contribution->report_number_id,
            'employer_code' => $employer->employer_code,
            'employer_name' => $employer->employer_name,
            'worked_date' => $report->ending_worked_date,
            'received_date' => $report->receipt_date,
            'report_local' =>  $contributionLocal,
            'reciprocal_local' => $reciprocalLocal,
            'unit_type' =>  $contribution->unitType->code_description,
            'units_worked' => $contribution->units_worked,
            'credited_units' => $contribution->units_credited,
            'rate' => $contribution->unit_multiplier,
            'reciprocal_rate' => $employerHours->reciprocal_multiplier,
            'calculated_amount' => money_format('%.2n', $contribution->calculated_amount),
            'received_amount' => money_format('%.2n', $contribution->actual_amount),
            'owed_amount' => money_format('%.2n', $contribution->owed_amount),
        ];

        return $response;
    }

贡献表中的一个字段是sub_hours。他们要我做的是保持所述场地的运行记录。在每个后续行中返回该标记为hours_to_date。所以在第一行sub_hours是32而在第二行它是60.在第一行hours_to_date将是32但在第二行它将是92而第三行它将是{{ 1}}等我似乎无法弄清楚如何跟踪这个运行的计数并允许变压器访问它。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

你能在变压器类上创建一个属性吗?我没有使用变形金刚,但有点像

class ContributionTransformer{
    private $tally;
    function __construct(){
        $this->tally = 0;
    }
    public function transform(Contribution $contribution){
        ...
            $this->tally += $contribution->sub_hours;
        ...
    }