zend2 mysql - 使用TableGateway连接表

时间:2015-05-13 08:46:01

标签: zend-framework2

我想从两个mySql表中获取数据:

SELECT L.id AS 'l_id', L.date, L.action, U.id AS 'u_id', U.name, U.surname 
FROM cases_log L, users U 
WHERE L.user = U.id 
LIMIT 0,30

所以,我决定使用$ select-> join,但它不能按照我想要的方式工作。它仅包含来自cases_log表的数据。

SELECT * 
FROM `cases_log` 
JOIN users 
ON users.id = cases_log.user 

Module.php:

'HistoryTable' =>  function($sm) 
{
    $tableGateway = $sm->get('HistoryTableGateway');
    $table = new HistoryTable($tableGateway);
    return $table;
},
'HistoryTableGateway' => function ($sm) 
{
    $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
    $resultSetPrototype = new ResultSet();
    $resultSetPrototype->setArrayObjectPrototype(new History());
    return new TableGateway('cases_log', $dbAdapter, null, $resultSetPrototype);
},

HistoryTable.php:

$table = $this->tableGateway;
$select = $table->getSql()->select();
//$select->from(array('L' => 'cases_log'))->join(array('U' => 'users'),'L.user = U.id');
$select->join('users', 'users.id = cases_log.user');

$select->limit(10);
$select->offset(0);         
$resultSet = $table->selectWith($select);

return $resultSet;

正如您所看到的,在注释行中,我尝试在$ select-> from中做了一些事情 - 但没有结果,因为$ select-> from是只读...

我是ZF2的新手所以,我想念一些吗?

1 个答案:

答案 0 :(得分:0)

$table = $this->tableGateway;
$select = $table->getSql()->select();
$select->columns(['l_id' => 'id', 'date', 'action']);
$select->join('users', 'users.id = cases_log.user', ['u_id' => 'id', 'name', 'surname']);
$select->limit(10);
$select->offset(0);

生成正确的sql(表的别名除外)