当前位置:  开发笔记 > 前端 > 正文

Laravel 5.1更新数据透视表列而不删除现有记录

如何解决《Laravel5.1更新数据透视表列而不删除现有记录》经验,为你挑选了1个好方法。

我在用Laravel 5.1.

我有两张桌子users并且medicinesmany-to-many关系.相关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'  );
    }
}

many-to-many关系表user_medicine具有一些额外的pivot columns,如下:

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

但是,不是updating现有many-to-many表格的时间栏,而是带有提供inserting药物和其他专栏的新记录.任何人都可以建议我在哪里犯错误?id = 1timenull



1> Tim..:

有一种方法updateExistingPivot可以使用:

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

最后一个参数指定是否应"触摸"父表,这意味着updated_at更新字段的时间戳.

推荐阅读
殉情放开那只小兔子
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有