doukan4795 2016-09-23 23:57
浏览 11
已采纳

一次保存所有相关记录

I am able to save associated records in cakephp3 but if you look at the code , the records are not saved all at once with 1 save call. I did have a problem trying to save all the records at once. If you look at how its done you see the Guardian and Users table are save separately. The code works and saves the records but saving all at once in 1 save call has been an issue as I got an error on the guardian table.

Guardians have a 1 to many relationship with students
Students and Users have a 1 to 1 
Students to subjects and availabilityFotStudents both have a many to many

Code

   public function add($gId=0) {
        $this->loadModel("Guardians");
        $this->loadModel('PaymentTypes');
        $this->set("title","Add Student");
        $guardians=null;


        if ($gId>0){
            $guardians =$this->Guardians->get($gId);
        }

        if ($this->request->is('post')) {

            if ( $this->request->data['studenttype']==0){ //enquiry
                $this->request->data['students']['address_billing'] = 0;
                 $this->request->data['students']['student_enq'] = 1;
            }
            else   if ( $this->request->data['studenttype']==1){ //waitlist
                $this->request->data['students']['address_billing'] = 1;
                 $this->request->data['students']['student_enq'] = 0;
            }
            else if ( $this->request->data['studenttype']==2){ //skip waitlist
                $this->request->data['students']['address_billing'] = 4;
                 $this->request->data['students']['student_enq'] = 0;
            }            

            if ( $this->request->data['students']['tutoring_typest_id']==1){
                $this->request->data['students']['group_status']=0;
            }
            else if ( $this->request->data['students']['tutoring_typest_id']>1){
                $this->request->data['students']['group_status']=1;
            }

            if ($this->request->data['students']['tutoring_typest_id']==3 ){//group only
                $this->request->data['students']['address_billing'] = 4;
            }

            $data = $this->request->data;
           // debug($data);



              $uname=  $this->request->data['Users']['username'];
              if ($this->Students->Users->findByUsername($uname)->count())  {
                $this->Flash->error(__('Username exists. Please, try again.'));
                return $this->redirect(["action"=>"add",$gId]);
               }
              $userId=0;

              $entity = $this->Students->Users->newEntity($this->request->data['Users'],['validate'=>false]);
              $entity->role = "student";
             $entity['role_id'] =  4;
              $entity = $this->Students->Users->save($entity);

          //  debug( $entity);
              $studentUserId =  $entity->id;


            if($guardians==null) {
                $guardians = $this->Guardians->newEntity($this->request->data['guardians'], ['validate' => false]);
            }

            $guardianEntity = $this->Guardians->save($guardians);
            $guardians = $this->Students->newEntity();
            $studentData = $this->request->data['students'];
            $studentData['subjects'] = $this->request->data['subjects'];
            $studentData['availability_for_students'] = $this->request->data['availability_for_students'];
            $studentEntity = $this->Students->patchEntity($guardians,$studentData,
                [
                    "validate"=>false,
                    'associated' => [
                        "AvailabilityForStudents"=>["validate"=>false],
                        "Subjects"=>["validate"=>false]
                    ]

                ]
            );
            $studentEntity->guardian_id = $guardianEntity->id;
            $studentEntity->user_id = $studentUserId;

            $studentEntity = $this->Students->save($studentEntity,
                [
                    "validate"=>false,
                    'associated' => [
                        "AvailabilityForStudents"=>["validate"=>false],
                        "Subjects"=>["validate"=>false]
                    ]

                ]
            );
            if ($studentEntity) {
                $this->Flash->success(__('The student has been saved'));
                return $this->redirect(["action"=>"index2"]);
            } else {
                $this->Flash->error(__('The student could not be saved. Please, try again.'),'flash_alert');
            }

        }//post
        $subjects = $this->Students->Subjects->find('list', array( 'order' => array('Subjects.name' => 'asc') ));
        $weekdays = $this->Students->weekDays;
        $tutoringTypes = $this->Students->TutoringTypeStudents->find('list');


        //$payments = $this->Student->paymentOptions;
        $this->PaymentTypes->primaryKey("name");
        $payments  = $this->PaymentTypes->find( 'list', array(
            'fields'     => array('PaymentTypes.name','PaymentTypes.name'))  );
        $referrals = $this->Students->Referrals->find('list');
        $tutorGender = $this->Students->Lessons->Tutors->tutorGender;

        $this->set('guardians', $guardians);
        $this->set(compact('referrals','subjects', 'tutoringTypes', 'weekdays','payments','tutorGender'));

    }
  • 写回答

1条回答 默认 最新

  • doremifasodo0008008 2016-10-04 05:58
    关注

    you can use Tranactional data save. Where you can run multiple save method. if any save method failed then no data will be save. so it works like "1 save call" which you mentioned

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?