laravel 5.2 - 用sum存储多个值

时间:2016-05-13 17:25:39

标签: laravel eloquent records

我有一个2表用户并报告

报告模型

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

用户模型

public function reports() {
    return $this->hasMany('App\Report', 'author_id');
}

在用户模型中,有一个名为" sum_sales"的列。 在报告模型中,有一个名为" total"

的列

我可以将报表模型中的总和(总计)传递给' sum_total'在我的用户模型中? 我的报告控制器

public function store(Request $request)
{
  $this->validate($request, ['title' => 'required',
                             'date' => 'required|date_format:d/m/Y|regex:/[0-9]{2}\/[0-9]{2}\/[0-9]{4}/',
                             'image_1' => 'required|mimes:png,jpeg',
                             'products' => 'required',
                             'total' => 'required',
                             'time' => 'required|min:2',
                             'location' => 'required',
                             'sub_location' => 'required',
                            ]);

  $user = Auth::user()->id;

  $report = new Report($request->all());
  $report->author_id = $user;

  $image = $request->file('image_1');
  $destinationPath = 'uploads/reports';
  $ext = $image->getClientOriginalExtension();
  $fileName = rand(11111,99999).'.'.$ext;

  $report->image_1 = $image->move($destinationPath, $fileName);

  $field_total = $request->input('total');
  $sum_total = $report->sum('total');
  $totalSum = $field_total + $sum_total;

  $report->author_id->sum_sales = $totalSum;    

  $report->save();

  Session::flash('flash_message', 'Report added!');

  return redirect('dash/reports');
}

有了这个浏览器说:

Indirect modification of overloaded property App\Report::$author_id has no effect

我怎么知道?

1 个答案:

答案 0 :(得分:0)

由GiedriusKiršys解决

public function store(Request $request)
{
  $this->validate($request, ['title' => 'required',
                             'date' => 'required|date_format:d/m/Y|regex:/[0-9]{2}\/[0-9]{2}\/[0-9]{4}/',
                             'image_1' => 'required|mimes:png,jpeg',
                             'products' => 'required',
                             'total' => 'required',
                             'time' => 'required|min:2',
                             'location' => 'required',
                             'sub_location' => 'required',
                            ]);

  $user = Auth::user()->id;

  $report = new Report($request->all());
  $report->author_id = $user;

  $image = $request->file('image_1');
  $destinationPath = 'uploads/reports';
  $ext = $image->getClientOriginalExtension();
  $fileName = rand(11111,99999).'.'.$ext;

  $report->image_1 = $image->move($destinationPath, $fileName);
  $report->save();

  $sumUserTotal = User::find($user)->reports->sum('total');
  Auth::user()->update(['sum_sales' => $sumUserTotal]);

  Session::flash('flash_message', 'Report added!');

  return redirect('dash/reports');
}