简体   繁体   English

仅在一个 Laravel 数据透视记录上更新附加列的问题

[英]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 .当尝试仅更新 pivot_table 的一条记录时,此方法会更新所有具有相同order_iduser_id记录。 Only records that match the order_id , user_id , status_id and finished_at = null should be updated.只应更新与order_iduser_idstatus_idfinished_at = null匹配的记录。

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:如果你只是从给定的 Order 中获取所有用户,你可以遍历他们并更新他们的数据透视记录,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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