zend-framework2 - 使用 ZF2 嵌套选择

标签 zend-framework2

尝试使用 Zend\Db\Sql\Select 获取嵌套选择并且在文档或谷歌上根本看不到任何内容。

想做这样的事情:

SELECT 
    table1.*,
    (SELECT x,y,z FROM table2 WHERE table2.a = table1.a) as b
FROM table1 

如果没有嵌套选择,它看起来像这样:
$select = new Zend\Db\Sql\Select;
$select
 ->columns(array(
    '*'
 ))
 ->from('table1')

ZF1 考虑创建一个 subSelect 项,然后将其添加为列列表中的表达式,但在 ZF2 中它提示表达式需要是字符串。

编辑:嵌套选择需要作为一列,因为在相同的列名上使用 GROUP BY 时我最终会得到相乘的行。这是我试图进入的正确查询 Zend\Db\Sql\Select :
SELECT
    users.id, 
    (SELECT count(explorations.id) FROM explorations WHERE user_id = users.id) as total_explorations, 
    count(villages.id)
FROM 
    users
INNER JOIN
    villages
        on (villages.user_id = users.id)
GROUP BY 
    users.id

最佳答案

Ralph Schindler 有一个他在 Zend\Db 中专门实现的不同 DB 模式的存储库。这是子选择之一:https://github.com/ralphschindler/Zend_Db-Examples/blob/master/example-20.php

内容是这样的:

<?php

/** @var $adapter Zend\Db\Adapter\Adapter */
$adapter = include ((file_exists('bootstrap.php')) ? 'bootstrap.php' : 'bootstrap.dist.php');
refresh_data($adapter);

use Zend\Db\Sql;
use Zend\Db\ResultSet\ResultSet;

$sql = new Sql\Sql($adapter);

$subselect = $sql->select();
$subselect->from('artist')
    ->columns(array('name'))
    ->join('album', 'artist.id = album.artist_id', array())
    ->where->greaterThan('release_date', '2005-01-01');


$select = $sql->select();
$select->from('artist')
    ->order(array('name' => Sql\Select::ORDER_ASCENDING))
    ->where
        ->like('name', 'L%')
        ->AND->in('name', $subselect);

$statement = $sql->prepareStatementForSqlObject($select);

$result = $statement->execute();

$rows = array_values(iterator_to_array($result));

assert_example_works(
    count($rows) == 2
    && $rows[0]['name'] == 'Lady Gaga'
    && $rows[1]['name'] == 'Linkin Park'
);

基本上,您可以使用一个选择作为另一个选择的谓词的值。

关于zend-framework2 - 使用 ZF2 嵌套选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14421156/

相关文章:

mysql - 发电机 : How to call dynamodb api from ZF2 rest application

mysql - 使用子查询将 mysql 查询转换为 zf2

zend-framework2 - 选择使用 Zend\Db\Sql 连接表时要返回的列

unit-testing - 运行所有 zend framework2 单元测试

zend-framework - 面向 Zend 框架新手的 Zend Framework 2

php - 在 Zend 2 应用程序中通过邮件报告错误

php - 服务未创建异常: ZF2

php - 如何包含扩展接口(interface)的 php 类

zend-framework2 - 如何从 Zend Framework 2 中的 View 文件访问路由、发布、获取、服务器等参数

php - Zend Framework 函数不是 Controller 中的操作