不删除现有记录的情况下更新 Laravel 5.1 中的 pivot 表列

3

我正在使用 Laravel 5.1

我有两个表,分别是usersmedicines,它们之间存在多对多的关系。相关的models如下所示:

class User extends BaseModel  {

    use SoftDeletes;
    protected $dates = ['deleted_at'];

    protected $table = 'users';

    public function medicines(){
        return $this->belongsToMany('App\Models\Medicine')->withPivot('id', 'time','config' ,'start','end' );
    }
}

并且。
class Medicine extends BaseModel{

    use SoftDeletes;
    protected $dates = ['deleted_at'];

    protected $table = 'medicines';

    public function users(){
        return $this->belongsToMany('App\Models\User')->withPivot('id', 'time','config' ,'start','end'  );
    }
}

以下是具有一些额外的pivot列多对多关系表user_medicine

id(PK) user_id(FK users) medicine_id(FK medicines) time   config        start       end 
1      1                 41                        09:00  {dispense:2}  2015-12-01  2015-12-25
2      1                 43                        10:00  {dispense:1}  2015-12-10  2015-12-22
3      1                 44                        17:00  NULL          2015-12-10  2015-12-31

现在,我想要更改特定药品的时间。我已经编写了以下代码:
public function updateMedicationTime($fields){

    $result = array();

    try {
        $user = User::find($fields['user_id']); 

        $medicines = $user->medicines()->where('medicines.id',$fields['medicine_id'])->first();

        if (!empty($medicines)){
            $medicine_times = json_decode($medicines->pivot->time);

            foreach ($medicine_times as $key=>$medicine_time ){

                if ($medicine_time->time == $fields['oldtime']){

                    $medicine_time->time = $fields['newtime'];
                }
            }

            // Update the time column of provided medicine id
            $user->medicines()->where('medicines.id',$fields['medicine_id'])->sync(array($medicines->id , array("time"=>json_encode($medicine_times))), false);

            // I also have tried 

            // $medicines->sync(array($medicines->id , array("time"=>json_encode($medicine_times))), false); OR 
            // $medicines->pivot->sync(array($medicines->id , array("time"=>json_encode($medicine_times))), false);

        }

    }
    catch(Exception $e ){
        throw $e;
    }

    return $result;
}

但是,与其更新现有的“多对多”表中的时间列,它会插入一条新记录,药品id = 1,并提供时间和其他列为null。有人能建议我在哪里犯了错误吗?

1个回答

6

你可以使用一种名为updateExistingPivot的方法:

$user = User::find($id);
$user->medicines()->updateExistingPivot($medicine_id, ['time' => $time], false);

最后一个参数指定是否应该“触摸”父表,这意味着updated_at字段的时间戳将被更新。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接