Exists statement for ZF2

In the next example you´ll see how to use an exists stament and how to use subqueries in ZF2.


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

$campos = array(
	'fecha_generacion' => 'fecha_generacion',
	'numero_envio' => new Expression('max(numero_envio)')
);

$subSelect = $sql->select();
$subSelect->columns(array('codigo_empresa'));
$subSelect->from(array('b' => 'documento_resumen'))
		->where('b.codigo_empresa = a.codigo_empresa')
		->where('b.tipo_documento = a.tipo_documento')
		->where('b.fecha_generacion = a.fecha_generacion')
		->where('b.codigo_respuesta = \'0\'');

$select = $sql->select()
	->quantifier(\Zend\Db\Sql\Select::QUANTIFIER_DISTINCT)
	->columns($campos)
	->from(array('a' => 'documento_resumen'))
		->where(
			array(
				'a.codigo_empresa' => $codigoEmp,
				'a.tipo_documento' => $tipoDoc,
				'a.codigo_respuesta' => '2'
			)
		);
$select->where->addPredicate(
		new \Zend\Db\Sql\Predicate\Expression(
		  "NOT EXISTS(" . @$subSelect->getSqlString($adapter->getPlatform()) . ")"
		)
	);
$select->group('a.fecha_generacion');

// Run the query
$statement = $sql->prepareStatementForSqlObject($select);
$result = $statement->execute();

return ArrayUtils::iteratorToArray($result);

Leave a Reply

Your email address will not be published. Required fields are marked *

en_USEN