Yii事务实战

来源:互联网 发布:百度云盘mac版下载 编辑:程序博客网 时间:2024/06/09 16:46

1.场景描述

添加题目

1.题目表

2.题目头表

3.选项表

控制器代码

public function actionadd()
{


$model = new ElectronicsrveryModel();
$post=array(
'eid'=>'100001',
'title'=>'zhang',
'desc'=>'20170819',
'createtime'=>date('Y:m:d H:i:s',time()),
'status'=>'1',
'scope'=>'1,2,3',
'endtime'=>date('Y:m:d H:i:s',time()+80000),
);
$post2=array(

'title'=>'zhang',
'desc'=>'20170819',
'type'=>1
);
$post3=array(
array(

'title'=>'zhang',
'optionflag'=>'A',
'answernum'=>0,
'type'=>1

),
array(

'title'=>'zhang',
'optionflag'=>'B',
'answernum'=>0,
'type'=>1

)

);
$model->add($post,$post2,$post3);
die;

}


数据层代码

public function add($post1,$post2,$post3)

{



 $connection = Yii :: app () -> db;
          $transaction = $connection -> beginTransaction ();

        
        try
        {
            // //eid,title,desc,createtime,endtime,deploytype,status,scope
            $sql = "insert into  syberos_electronicsurvey(eid,title,`desc`,createtime,endtime,`status`,scope) values('$post1[eid]','$post1[title]','$post1[desc]','$post1[createtime]','$post1[endtime]','$post1[status]','$post1[scope]')";

            $cmd = $connection -> createCommand ( $sql );

            $res=$cmd ->execute();
   $sql=" SELECT LAST_INSERT_ID() as id";

              $cmd = $connection -> createCommand ( $sql );

            $res=$cmd ->queryRow();

            //surveyid,title,desc,type
            $sql = "insert into  syberos_electronicsurvey_question(surveyid,title,`desc`,type) values('$res[id]','$post2[title]','$post2[desc]','$post2[type]')";

            $cmd = $connection -> createCommand ( $sql );
            $result = $cmd -> execute ();




//questionid,title,optionflag,answernum,type
foreach($post3 as $val)
{
$sql = "insert into  syberos_electronicsurvery_option(questionid,title,optionflag,answernum,type) values('$res[id]','$val[title]','$val[optionflag]','$val[answernum]','$val[type]')";

$cmd = $connection -> createCommand ( $sql );
$result = $cmd -> execute ();
            }
            $transaction -> commit ();



        }
        catch ( Exception $e )
        {
            $result = false;
var_dump($e->getMessage());
            $transaction -> rollBack ();
        }





}