CakePHP搜索多个模型

时间:2017-05-15 11:53:42

标签: php cakephp associations conditional-statements cakephp-3.x

我有一个名为用户的表格,它与教练客户相关联。

我想在用户表和教练表中搜索。

我的表格如下:

CREATE TABLE IF NOT EXISTS `team07`.`users` (
  `id` INT(11) NOT NULL,
  `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,
  PRIMARY KEY (`id`),
  UNIQUE INDEX `email_UNIQUE` (`email` ASC))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;

CREATE TABLE IF NOT EXISTS `team07`.`coaches` (
  `id` INT NOT NULL,
  `coachid` INT NOT NULL,
  `appstate` INT NOT NULL,
  `bio` VARCHAR(2048) NULL,
  `price` INT NULL,
  PRIMARY KEY (`id`),
  INDEX `COACH_INFOFK_idx` (`coachid` ASC),
  UNIQUE INDEX `coachid_UNIQUE` (`coachid` ASC),
  CONSTRAINT `COACH_INFOFK`
    FOREIGN KEY (`coachid`)
    REFERENCES `team07`.`users` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

这就是我正在做的代码:

  public function review()
    {
      //Select all users which are a Coach AND have appstate = 1 (Just signed up, in review)     
      $users = $this->paginate($this->Users);
      $users = $this->Users->find('all')->where(['Users.usertype'=>'CO', 'Coaches.appstate'=>'1']);

      $this->set(compact('users'));
      $this->set('_serialize', ['users']);
    }

但是我遇到了问题,因为我的页面以

响应
  

错误:SQLSTATE [42S22]:找不到列:1054未知列   'where子句'中的'Coaches.appstate'

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

如果蛋糕理解了关联,您可以使用contains来加载它: https://book.cakephp.org/3.0/en/orm/query-builder.html#loading-associations

这样的事情:

public function review()
{
    //Select all users which are a Coach AND have appstate = 1 (Just signed up, in review)     
    $users = $this->paginate($this->Users);
    $users = $this->Users->find('all')->contain(['Coaches'])->where(['Users.usertype'=>'CO', 'Coaches.appstate'=>'1']);

    $this->set(compact('users'));
    $this->set('_serialize', ['users']);
}