在 CakePHP 中从一个模型创建多个模型

Creating multiple models from one model in CakePHP

我有一个 users 和一个 clients table.

它们的链接如下:

-- -----------------------------------------------------
-- Table `users`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `users` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `email` VARCHAR(45) NOT NULL,
  `password` VARCHAR(255) NOT NULL,
  `usertype` CHAR(2) NOT NULL,
  `created` DATETIME NOT NULL,
  `modified` DATETIME NULL DEFAULT NULL,
  `firstname` VARCHAR(45) NOT NULL,
  `lastname` VARCHAR(45) NOT NULL,
  `phonenumber` VARCHAR(45) NOT NULL,
  `suburb` VARCHAR(45) NOT NULL,
  `state` VARCHAR(10) NOT NULL,
  `businessname` VARCHAR(45) NULL DEFAULT NULL,
  `image` BLOB NULL DEFAULT NULL,
  `valid` INT NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE INDEX `email_UNIQUE` (`email` ASC))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
-- -----------------------------------------------------
-- Table `clients`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `clients` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `user_id` INT NOT NULL,
  PRIMARY KEY (`id`),
  INDEX `CLIENTS_FK_idx` (`user_id` ASC),
  CONSTRAINT `CLIENTS_FK`
    FOREIGN KEY (`user_id`)
    REFERENCES `users` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

我已经烘焙了这两个 table 并且我创建了一个用户注册页面。提交表单后,我希望数据库同时创建一个 user 和一个 client 对象。

这是 CakePHP 中我的 UsersController 方法:

  public function clientregistration()
    {
      //Register a new client. Client enters all details and the system sets usertype=CL
      $user = $this->Users->newEntity();
        if ($this->request->is('post')) {
            $user = $this->Users->patchEntity($user, $this->request->getData());
            $user->usertype = 'CL';
            $user->valid = 1;

            if ($this->Users->save($user) && $this->Coaches->($coach)) {
                $this->Flash->success(__('You have successfully registered.'));

                return $this->redirect(['action' => 'login']);
            }
            $this->Flash->error(__('Registration failure. Please, try again.'));
        }
        $this->set(compact('user'));
        $this->set('_serialize', ['user']);

我希望代码自动预填充 客户端 table 中的所有数据。

我该怎么做?

我不知道你要预填什么,你只有 user_id 字段要保存。因此,如果您的关联在 UsersTable.php 中设置正确,您可以在保存用户后保存客户实体:

$client = $this->Users->Clients->newEntity();
$client->user_id = $user->id;
$this->Users->Clients->save($client);