【问题标题】:cakephp3 own query buildercakephp3 自己的查询生成器
【发布时间】:2018-11-24 18:51:36
【问题描述】:

我是 cakephp 新手,我正在关注教程,我来自其他语言,我不习惯阅读这样的查询:

   public function findTagged(Query $query, array $options)
    {
        $columns = [
            'Articles.id', 'Articles.user_id', 'Articles.title',
            'Articles.body', 'Articles.published', 'Articles.created',
            'Articles.slug',
        ];

        $query = $query
            ->select($columns)
            ->distinct($columns);

        if (empty($options['tags'])) {
            // If there are no tags provided, find articles that have no tags.
            $query->leftJoinWith('Tags')
                ->where(['Tags.title IS' => null]);
        } else {
            // Find articles that have one or more of the provided tags.
            $query->innerJoinWith('Tags')
                ->where(['Tags.title IN' => $options['tags']]);
        }

        return $query->group(['Articles.id']);
    }

这是一个简单的查询,很容易理解,但是如果我有一个更复杂的查询,有很多连接等,有没有可能用 sql sintax 编写自己的查询,你能帮我把这段代码翻译成用sql写的查询?

谢谢

【问题讨论】:

    标签: mysql cakephp-3.0


    【解决方案1】:

    您可以使用$connection->execute() (https://book.cakephp.org/3.0/en/orm/database-basics.html#running-select-statements) 直接编写执行 SQL 查询,但我建议坚持使用 cakephp 的 ORM。

    如果您想知道上面发布的查询如何转换为 SQL,我建议您使用 DebugKit。如果您的应用程序配置中有 debug = true,当您在浏览器中打开应用程序时,您将在右下角看到这个红色矩形。点击它并点击“Sql queries”:你会在上面的某个地方找到从上面的查询生成的SQL。或者,您可以使用查询日志记录(请参阅此处:https://book.cakephp.org/3.0/en/orm/database-basics.html#database-query-logging

    【讨论】:

    • 谢谢,但我正在尝试使用 debugkit 但我缺少一些东西;我已经在 application.php 中启用了它,但我在页面上什么也看不到,还在配置中添加了代码:book.cakephp.org/3.0/en/debug-kit.html
    • 很难猜测会发生什么。在您的 config/bootstrap.php 中,您看到这一行 Plugin::load('DebugKit', ['bootstrap' => true]); 吗? tmp目录下有debug_kit.sqlite文件吗?
    • 解决了!看来您需要一个名为 debug_kit 的数据库
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多