11

我正在把这个 sql 变成 zend 框架 sql 模式。

SELECT 
    jobs . *,
    c.id AS cid,
    c.name AS name,
    c.companyImage AS companyImage,
    c.logo AS logo,
    count(app.userId) AS t_app,
    app.applyStatus AS applyStatus,
    app.userId AS appUserId
FROM
    jobs
        LEFT JOIN
    companies AS c ON jobs.companyName = c.id
        LEFT JOIN
    applicants AS app ON jobs.id = app.jobId AND app.applyStatus = 1
WHERE
    jobs.ownerId = 16 AND jobs.draftId != 0 
GROUP BY jobs.id
ORDER BY jobs.id DESC
LIMIT 3 

对于这个 sql,我已经为 zend 框架 2 编写了这个代码

$adapter = $this->tableGateway->getAdapter();
        $sql     = new Sql($adapter);

        $select = $sql->select();
        $select->from('jobs')
                ->join(array('c' => 'companies'), 'jobs.companyName = c.id', array('cid' => 'id', 'name', 'companyImage', 'logo'), 'left')
                ->join(array('app' => 'applicants'), ' jobs.id = app.jobId AND app.applyStatus = 1', array('t_app'     => new Expression('count(app.userId)'), 'applyStatus', 'appUserId' => 'userId'), 'left')
                ->where("jobs.ownerId ={$userId} AND jobs.draftId != 0")
                ->group('jobs.id')
                ->order('jobs.id DESC')
                ->limit(3);

        $statement = $sql->getSqlStringForSqlObject($select);
        $results   = $adapter->query($statement, $adapter::QUERY_MODE_EXECUTE);

但不能正常工作,它会给出如下消息。

SQLSTATE[42S22]: Column not found: 1054 Unknown column '1' in 'on clause'
4

3 回答 3

17

问题是这部分:

app.applyStatus = 1

框架正在转义 1 ,就好像它是列名1.

您也需要将此部分包含在表达式中

new Expression('jobs.id = app.jobId AND app.applyStatus = 1')

我认为在 join 方法的 'ON' 参数中使用 Expressions 可能取决于您使用的 ZF2 版本,我认为它是在 2.1+ 中添加的

于 2013-05-20T09:11:25.627 回答
3

基于这个答案。如果您还希望对表和列标识符进行转义,请使用以下语法:

use Zend\Db\Sql\Expression;

...

$onExpression = new Expression('? = ? AND ? = ?', 
    ['jobs.id', 'app.jobId', 'app.applyStatus', 1], 
    [Expression::TYPE_IDENTIFIER, Expression::TYPE_IDENTIFIER, 
     Expression::TYPE_IDENTIFIER, Expression::TYPE_LITERAL]
);

$select->from('jobs')
    ->join(array('app' => 'applicants'), $onExpression, array('t_app' => new Expression('count(app.userId)'), 'applyStatus', 'appUserId' => 'userId'), 'left');

Expression 构造函数接受字符串,然后是参数,然后是参数类型。

public function __construct($expression = '', $parameters = null, array $types = [])
于 2015-10-12T17:37:57.953 回答
0

这将产生一个安全问题。Zf2 将您的查询更改为:

Select * from tableA inner join tableB 
on `tableA`.`column` = `tableB`.`column` 
AND `tableB`.`column` = `1`

它增加了

`

到每个部分的安全问题!通过使用new Expression你绕过它,如果你applyStatus从用户输入中获得,请确保它的过滤!

于 2015-01-17T18:41:03.480 回答