一种更新数据的方法

//先查原先文章所属栏目
$result = Db::name('Tablename')->alias('con')
->field('`con`.`weiba_id`')
->join('Tablename1 wb', 'con.weiba_id=wb.weiba_id','left')
->where("wb.uid=$uid and con.post_id=$data[post_id]")
->select();
$data_old['weiba_id']=[];

if($result){
foreach($result as $k=>$v)  {
$data_old['weiba_id'][] = $v['weiba_id'] ;
}
}
//dump($data_old);die;
$count_old=count($data_old['weiba_id']);
$count_new=count($data['weiba_id']);
       //接下来,进行判断,先用旧的和新的进行比较,如果不存在,则删除旧的
$bz_connection = Db::name('Tablename');
        for($i=0;$i<$count_old;$i++){
            $g=0;
          for($j=0;$j<$count_new;$j++){
          if($data_old['weiba_id'][$i]==$data['weiba_id'][$j]){
       $g=1;
       break;
           }
             }
          if($g==0){
         $bz_connection->where(array('post_id'=>$data['post_id'],'weiba_id'=>$data_old['weiba_id'][$i]))->delete();
           }
        }
//换过来,进行判断,再用新的和旧的进行比较,如果不存在,则添加一条记录
for($i=0;$i<$count_new;$i++){
$g=0;
for($j=0;$j<$count_old;$j++){
if($data['weiba_id'][$i]==$data_old['weiba_id'][$j]){
$g=1;
break;
}
}
if($g==0){
$insert = array('post_id'=> $data['post_id'] , 'weiba_id'=> $data['weiba_id'][$i]);
$bz_connection->insert($insert,false,true);
}
}

你可能感兴趣的:(学习笔记)