在CakePHP 3中评估的是哪个顺序和Where(),或Where(),where()方法?

时间:2017-04-27 11:32:41

标签: php mysql sql cakephp

我对CakePHP 3文档查询生成器的高级条件中的内容感到困惑:https://book.cakephp.org/3.0/en/orm/query-builder.html#advanced-conditions

它提供以下代码

$query = $articles->find()
->where(['author_id' => 2])
->orWhere(['author_id' => 3])
->andWhere([
    'published' => true,
    'view_count >' => 10
])
->orWhere(['promoted' => true]);

并说这相当于这个SQL:

SELECT *
FROM articles
WHERE (promoted = true
OR (
  (published = true AND view_count > 10)
  AND (author_id = 2 OR author_id = 3)
))

我根本不了解其工作原理,因为PHP中的条件顺序与生成的SQL语句中的顺序不同(例如->orWhere(['promoted' => true])在PHP语句中是最后一个,但在SQL语句中是第一个。为什么?)。

文档中唯一可能相关的信息是:

  

每个方法设置当前和之间使用的组合运算符   以前的条件。

这是文档中的错误,还是有人可以用更好的方式解释这是如何工作的?

虽然我意识到这几乎肯定是错的,但我对SQL将如何评估的理解是:

SELECT *
FROM articles
WHERE (author_id = 2 OR author_id = 3)
AND ( (published = true AND view_count > 10) OR promoted = true)

1 个答案:

答案 0 :(得分:1)

当你使用orWhere查询构建器时,它会占用整个where子句,并将其设置在OR运算符的一侧,这就是为什么它是这样的

public static void ReadFromExcell(String file) throws IOException, GeneralSecurityException {
    String excelFilePath = "ServerList.xlsx";

    try {
        NPOIFSFileSystem fileSystem = new NPOIFSFileSystem(new File(excelFilePath));
        EncryptionInfo info = new EncryptionInfo(fileSystem);
        Decryptor decryptor = Decryptor.getInstance(info);

        if (!decryptor.verifyPassword("qwerty")) {
            System.out.println("Unable to process: document is encrypted.");
            return;
        }

        InputStream dataStream = decryptor.getDataStream(fileSystem);

        Workbook workbook = new XSSFWorkbook(dataStream);
        Sheet firstSheet = workbook.getSheetAt(0);
        Iterator<Row> iterator = firstSheet.iterator();

        while (iterator.hasNext()) {
            Row nextRow = iterator.next();
            Iterator<Cell> cellIterator = nextRow.cellIterator();

            while (cellIterator.hasNext()) {
                Cell cell = cellIterator.next();
                System.out.print(cell.getStringCellValue() + "\t");
            }
            System.out.println();
        }

        workbook.close();
        dataStream.close();
        fileSystem.close();
    } catch (GeneralSecurityException | IOException ex) {
        ex.printStackTrace();
    }
}

你必须像这样来获得所需的输出

WHERE (
   promoted = true
   OR 
   (
      (published = true AND view_count > 10)
      AND 
      (author_id = 2 OR author_id = 3)
   )
)

OR

    $query = $this->Orders->find()
        ->where(['author_id' => 2])
        ->orWhere(['author_id' => 3])
        ->andWhere([
            'OR'=>[
                ['promoted' => true],
                ['published' => true,
                    'view_count >' => 10]
            ]
        ]);