php - CakePHP 与内部连接

标签 php mysql cakephp inner-join

我需要使用 CakePHP find 方法执行以下查询:

SELECT * FROM `ads`
INNER JOIN fields_values ON fields_values.ref_id = ad.id 
WHERE ad.active = 1

我尝试了这个功能,但她不起作用:

$ads = $this->Ad->find('all', array(
            'joins' => array(
                array(
                    'table' => 'fields_values',
                    'alias' => 'fv',
                    'type' => 'INNER',
                    'conditions' => array(
                        "Ad.id = fv.ref_id "
                    )
                )
            ),
            'conditions' => array(
                'Ad.active' => 1
            ),
        ));

最佳答案

你的查询是错误的,应该是

SELECT * FROM `ads`
INNER JOIN fields_values as fv ON fv.ref_id = ads.id 
WHERE ads.active = 1

现在您可以使用蛋糕查询来构建它。哪个左连接也可以做到这一点。

$ads = $this->Ad->find('all', array(
            'conditions' => array(
                'Ad.active' => 1
            ),
            'joins' => array(
                array(
                    'table' => 'fields_values',
                    'alias' => 'fv',
                    'type' => 'LEFT',
                    'conditions' => array(
                        "fv.ref_id = Ad.id",
                        // or you can add the top condition here
                        //'Ad.active' => 1
                    )
                )
            ),
        ));

关于php - CakePHP 与内部连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32244995/

相关文章:

php - 在特定时间更改数据库字段

php - mysql中插入特殊字符

php - 披萨数据库优化

CakePHP 1.3 替代 SoftDeletable 行为?

php - PHP 中的等距柱状近似

mysql - Joomla:如何检测我们表中的列是否存在,如果不存在则将其添加到表中

c++ - sql::SQLString 行为

mysql - CakePHP 中清理 SQL 的所有方法

mysql - 具有多个连接、group_concat 和百万行的查询执行缓慢

php - cron 如何根据日期输出到新的日志文件?