简体   繁体   中英

Problems updating additional column on just one Laravel pivot record

When trying to update just one record of a pivot_table, this method updates all records with the same order_id and user_id . Only records that match the order_id , user_id , status_id and finished_at = null should be updated.

public function pause($id)
{
    $order = Order::find($id);
    $now = Carbon::now();
    $stage = Status::find($order->status_id)->stage_id;

    $users = $order
        ->user()
        ->where('status_id', $order->status_id)
        ->where('finished_at', null)
        ->get();

    foreach($users as $user)
    {
        $user->pivot->finished_at = $now;
        $user->pivot->save();
    }

    flash()->success('Progress paused for order #' . $order->order_number .'.');
    return redirect('/department/' . $stage);

}

Before running pause method: 运行暂停方法前的图像

After running pause method: 运行暂停方法后的图像

If you just grab all the users from the given Order, you can iterate through them and update their pivot records like so:

// set finished_at time for all users
foreach($users as $user)
{
    $user->order()
         ->wherePivot('status_id', $order->status_id)
         ->wherePivot('finished_at', null)
         ->updateExistingPivot($order->id, [ 'finished_at' => $now ], false);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM