如何将数据插入 Codeigniter 4 中的 2 个表

How to insert data into 2 tables in Codeigniter 4

我有 3 个 table、2 个 table(组和用户)和 1 个 table 组和用户之间的关系(users_groups)。

Table 组:

Tables 个用户:

Table users_groups:

我有一个表格可以输入 name_user、电子邮件和 group_id。但是,它只是添加到 table 个用户中。

型号代码:

public function saveAdmin($data_user, $data_group){
        return $this->db->table('users')->insert($data_user);

        $data_group['user_id'] = $this->db->insertID();
        return $this->db->table('users_groups')->insert( $data_group);
    }

控制器

public function save()
    {
        $data_user = array(
            'first_name'        => $this->request->getPost('first_name'),
            'email'             => $this->request->getPost('email'),
            'password'          => $this->request->getPost('password')
        );
      
        $data_group = array(
            'group_id'    => $this->request->getPost('group_id')
        );    
      
        $this->userModel->saveAdmin($data_user, $data_group);
        return redirect()->to(base_url('SAdmin/dataAdmin'));
    }

查看

<form action="<?= base_url('SAdmin/DataAdmin/save'); ?>" method="post">
 <label class="col-sm-4 col-form-label">Nama</label>
 <input type="text" class="form-control" id="first_name" placeholder="Nama">
                                     
 <label class="col-sm-4 col-form-label">Email</label>
 <input type="text" class="form-control" name="email" placeholder="Email">
    
 <label class="col-sm-4 col-form-label">Unit</label>
 <select name="group_id" class="form-control">
  <option value="">-Pilih-</option>
  <?php foreach($unitadmin as $row):?>
  <option value="<?= $row['id'];?>"><?= $row['description'];?></option>
 <?php endforeach;?>
 </select>

</form>

我想把数据添加到users_group和用户中,怎么办?先谢谢了

您在 Model 上完成全部任务之前使用了 return 关键字。因此,您需要使用此代码更改 Model

 public function saveAdmin($data_user, $data_group) {
      $this->db->table('users')->insert($data_user);
      $data_group['user_id'] = $this->db->insertID();
      return $this->db->table('users_groups')->insert( $data_group);
  }