2016-05-13 114 views
1

存儲多個值,我有一個2表用戶,並報告laravel 5.2 - 與和

報表模型

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

用戶模型

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

在用戶模式有一個叫列「 sum_sales「 在報告模型中有一列稱爲」總計「

何我可以通過我的報告模型中的總和(總數)到我的用戶模型中的'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 

我怎樣才能弄清楚?

+0

代替'$報告 - > author_id-> sum_sales',寫'$用戶> sum_sales',你應該是好去。 –

+0

我嘗試,但扔我:**嘗試分配非對象的屬性** – user0111001101

+1

哎呀,沒有注意到'$ user'只是一個id。然後寫'Auth :: user() - > update(['sum_sales'=> $ totalSum])''。確保'sum_sales'屬性是可填充數組。 –

回答

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'); 
}