CakePHP 3.6嵌套子查询

时间:2018-06-18 13:06:55

标签: cakephp cakephp-3.x

我有以下表格。

  CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    group_id INT(11) NOT NULL,
    username VARCHAR(255) NOT NULL,
    name VARCHAR(255) NOT NULL,
    password VARCHAR(255) NOT NULL,
    email VARCHAR(255) NOT NULL,
    lastlogin DATETIME DEFAULT NULL,
    published BOOLEAN DEFAULT TRUE,
    created DATETIME DEFAULT NULL,
    modified DATETIME DEFAULT NULL,
    UNIQUE KEY (username)
);

CREATE TABLE companies (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    created DATETIME DEFAULT NULL,
    modified DATETIME DEFAULT NULL,
    UNIQUE KEY (name)
);

CREATE TABLE locations (
    id INT AUTO_INCREMENT PRIMARY KEY,
    company_id INT(11) NOT NULL,
    uuid BINARY(36) NOT NULL,
    name VARCHAR(255) NOT NULL,
    clock_id INT(11) NOT NULL,
    created DATETIME DEFAULT NULL,
    modified DATETIME DEFAULT NULL,
    FOREIGN KEY location_company_key (company_id) REFERENCES companies(id),
);

现在,我想选择分配给登录用户的公司下列出的所有位置;

$companies = $this->Locations->Companies->find()
    ->select(['Companies.id'])
    ->matching('Users', function ($q) {
        return $q->where(['Users.id' => $this->Auth->User('id')]);
    });

$locations = $this->Locations->find()
    ->where(['company_id IN' => $companies]);

但由于某种原因,我没有得到预期的结果。有人知道如何解决?

1 个答案:

答案 0 :(得分:0)

我的代码是正确的,我在数据库中没有正确的样本值

$companies = $this->Locations->Companies->find()
    ->select(['Companies.id'])
    ->matching('Users', function ($q) {
        return $q->where(['Users.id' => $this->Auth->User('id')]);
    });

$locations = $this->Locations->find()
    ->where(['company_id IN' => $companies])
    ->contain(['Companies']);