Cakephp中的UNION语法

ban*_*cer 11 php mysql sql union cakephp

有人知道在CakePHP中进行UNION查询的好方法吗?我想避免使用$this->query();.

有两个表t1,t2:

SELECT * FROM t1
LEFT JOIN t2 ON t1.id = t2.id
UNION
SELECT * FROM t1
RIGHT JOIN t2 ON t1.id = t2.id
Run Code Online (Sandbox Code Playgroud)

有三个表t1,t2,t3:

SELECT * FROM t1
LEFT JOIN t2 ON t1.id = t2.id
LEFT JOIN t3 ON t2.id = t3.id
UNION
SELECT * FROM t1
RIGHT JOIN t2 ON t1.id = t2.id
LEFT JOIN t3 ON t2.id = t3.id
UNION
SELECT * FROM t1
RIGHT JOIN t2 ON t1.id = t2.id
RIGHT JOIN t3 ON t2.id = t3.id
Run Code Online (Sandbox Code Playgroud)

Chu*_*ess 13

太多的程序员试图将自己局限于框架的功能.别.使用框架提供的内容.如果它没有您寻求的功能,那么:

  • 将您需要的功能编码到类扩展中

要么

  • 自定义在框架内旋转代码以满足您的需求.

通常情况下,开发人员会尝试将一个方形钉子敲入一个圆孔中,然后做太多额外的工作,这实际上只会使代码变得复杂.退后一步,问一下为什么要开始使用框架.它为非结构化语言带来了结构.它为构建应用程序提供了坚实的可重用基础.它并不是一个让自己陷入困境的盒子.

更新:我花了一分钟阅读复杂的查找条件,并找到了答案:

$joins = array(
    array(
        'table' => 'test_twos',
        'alias' => 'TestTwo',
        'type' => 'LEFT',
        'conditions' => array(
            'TestTwo.id = TestOne.id',
        )
    ),
    array(
        'table' => 'test_threes',
        'alias' => 'TestThree',
        'type' => 'LEFT',
        'conditions' => array(
        'TestThree.id = TestOne.id',
    )
    )
);

$dbo = $this->getDataSource();
$subQuery = $dbo->buildStatement(
    array(
        'fields' => array('*'),
        'table' => $dbo->fullTableName($this),
        'alias' => 'TestOne',
        'limit' => null,
        'offset' => null,
        'joins' => $joins,
        'conditions' => null,
        'order' => null,
        'group' => null
    ),
    $this->TestOne
);
$query = $subQuery;

$query .= ' UNION ';
$joins = array(
    array(
        'table' => 'test_twos',
        'alias' => 'TestTwo',
        'type' => 'LEFT',
        'conditions' => array(
            'TestTwo.id = TestOne.id',
        )
    ),
    array(
        'table' => 'test_threes',
        'alias' => 'TestThree',
        'type' => 'RIGHT',
        'conditions' => array(
        'TestThree.id = TestOne.id',
        )
    )
);

$dbo = $this->getDataSource();
$subQuery = $dbo->buildStatement(
    array(
    'fields' => array('*'),
    'table' => $dbo->fullTableName($this),
    'alias' => 'TestOne',
    'limit' => null,
    'offset' => null,
    'joins' => $joins,
    'conditions' => null,
    'order' => null,
    'group' => null
    ),
    $this->TestOne
);

$query .= $subQuery;

pr($query);
Run Code Online (Sandbox Code Playgroud)

  • 首先要做的是检查是否可以解决框架功能的问题.当然,框架不能限制程序员. (4认同)

Mat*_*ier 5

我们目前使用的一种简单方法是在MySQL或您使用的任何数据库中创建视图.然后,您可以使用视图,而不是在模型中使用表格.您可以在此处阅读有关视图创建语法的信息:http://dev.mysql.com/doc/refman/5.6/en/create-view.html.您还可以使用HeidiSQL等软件来帮助您创建视图.

然后你会在你的模型中有这样的东西:

class Contenu extends AppModel {
    public $useTable = 'v_contenu';
Run Code Online (Sandbox Code Playgroud)

这允许你仍然使用find()CakePHP中的方法,这是非常好的.

要获得视图的最佳性能,您应该将MySQL更新到至少5.6版.