在 Zend Framework 2 中左连接变量 Select

Left join with variable in Zend Framework 2 Select

我正尝试在 Zend Framework 2 中执行以下操作 select:

$select->from($this->table);
    $select->join($this->multiLangTable, $this->table . '.id=' .$this->multiLangTable . '.'
            . $this->foreignKey .' AND '. $this->multiLangTable . ".lang =".$locale, $mapping, 'left');

变量 $locale 是我的应用程序的语言(ca、es、en)。问题是应用程序显示和错误提示:

Statement could not be executed (42S22 - 1054 - Unknown column 'ca' in 'on clause')

它将变量检测为列,但它不是列。

我以前也试过,但还没有找到好的方法。这是因为 Zend 只是将 on 语句中的所有内容都作为标识符引用。您可以将条件移动到 where 语句

$select->from($this->table);
$select->join($this->multiLangTable, $this->table . '.id=' .$this->multiLangTable . '.'
            . $this->foreignKey, $mapping, \Zend\Db\Sql\Select::JOIN_LEFT);
$select->where(array($this->multiLangTable . ".lang" => $locale));

或者您可以在 on 语句中使用 \Zend\Db\Sql\Expression,但这会从中删除所有 qouting。

$select->join($this->multiLangTable,new \Zend\Db\Sql\Expression($this->table . '.id=' .$this->multiLangTable . '.'
        . $this->foreignKey .' AND '. $this->multiLangTable . ".lang = ? ", $locale), $mapping, 'left');

我找到了适合我的解决方案。

 $select->from($this->table);
 $select->join($this->multiLangTable,new \Zend\Db\Sql\Expression( $this->table . '.id=' .$this->multiLangTable . '.'
            . $this->foreignKey . ' AND '.$this->multiLangTable . '.lang = ?'), $mapping, 'left');
 $statement = $sql->prepareStatementForSqlObject($select);

 $resultsSql = $statement->execute(array($locale));