我正在创建一个应用程序,用户可以在其中发起挑战,看看谁减重最多。有 1 个挑战表,有一个 id、user_id(fk)、weight 和 week。为了每周在前端显示它们,我制作了一个新数组。用户控制器: public function index() { $users = User::all(); // get all challanges descending $challanges = Challange::orderBy('week', 'DESC')->get(); // make an array for every [week] that has an array with ['user' => 'weight'] in user_id order $weightArray = array(); // how long is the list depending on amount of weeks $startweek = 1; $endweek = Challange::max('week'); // go through every week for ($i = $startweek; $i <= $endweek; $i++) { // get weight foreach user and if no value set 0 foreach ($users as $user) { // get challange values per week $challenge = $user->challanges()->where('week', '=', $i)->get(); // if there is a challange if (count($challenge) > 0) { // set a weight value for that user *!!FIX make weigt alue unique!!* $weightArray[$i][$user->id] = $challenge[0]->weight; } else { // set 0 if no weight isset $weightArray[$i][$user->id] = 0; } } } return view('dashboard', compact('users', 'weightArray')); }当用户登录并按下更新时,会有一个表单提供隐藏输入 Auth::user()->id 和星期。用户必须自己输入的重量。这会返回一个请求,但现在我不知道如何匹配周和 user_id,以找到需要更新权重的 id。挑战控制器:public function update(Request $request) { $week = $request->week; $challange = Challange::find($request->user_id)->where('week', $week); dd($challange); }这将返回:错误调用成员函数 where() on null我应该预先在数组中添加 id 吗?还是我 where('user_id', $user_id) 并在返回的数组上执行另一个 where ?我不知道该怎么办。有人可以帮忙吗?
1 回答
交互式爱情
TA贡献1712条经验 获得超3个赞
顺序错误。你应该 :
$challange = Challange::where('week', $week)
->where('user_id', $request->user_id)
->first();
// or
$challange = Challange::where([
'week' => $week,
'user_id' => $request->user_id
])->first();
- 1 回答
- 0 关注
- 137 浏览
添加回答
举报
0/150
提交
取消