如何获得这样的Sql:
select * from foo where LOWER(foo_name) = 'test';
我得到的是如果Sql \ Expression在右边,而不在左边。
答案 0 :(得分:17)
您可以像这样使用代码段。
$where = new Where();
$sql = new Sql($adapter);
$select = $sql->select();
$where->addPredicate(new Predicate\Expression('LOWER(foo_name) = ?', 'test' ));
$select->from('foo')->where($where);
但是我不认为在Zend Framework 2上可以使用右侧的Sql \ Expression。
答案 1 :(得分:5)
你可以这样做:
$sql = new SQL($adaptor);
$select = $sql->select()->from(array('f'=>'foo'));
$select = $select->where('foo_name' => new \Zend\Db\Sql\Expression("LOWER('test')"));
以上查询将返回:
SELECT `f`.* FROM `foo` AS `f` WHERE `foo_name` = LOWER('test');
答案 2 :(得分:0)
对于寻找类似的其他人来说,从ZF 2.2开始实际上有很多不同的方法
链接(与接受的答案相同)
<?php
$sql = new Sql($adapter);
$select = $sql->select();
$select->from( array( 'f' => 'foo' ) )
->where
->addPredicate( new Predicate\Expression( 'LOWER(f.foo_name) = ?', 'test' ) );
//SELECT `f`.* FROM `foo` AS `f` WHERE LOWER(f.foo_name) = :where1
//:where1 = 'test'
?>
请注意,缺少Select :: $的执行命令“()”,允许您继续方法链接。 Select :: $ where有一个__get Magic方法catch,它返回Select对象中受保护的Select :: $ _ where属性,该对象是Sql \ Where的实例。
Predicate \ Literal 1
<?php
$select->where( "LOWER(f.foo_name) = 'test'" );
//SELECT `f`.* FROM `foo` AS `f` WHERE LOWER(f.foo_name) = 'test'
?>
Predicate \ Literal 2
<?php
$select->where( array( "LOWER(f.foo_name) = 'test'" ) );
//SELECT `f`.* FROM `foo` AS `f` WHERE LOWER(f.foo_name) = 'test'
?>
如果提供给Select :: where方法的数组或参数的索引值(列标识符)是字符串,则上面两个会自动为您创建一个Predicate \ Literal对象。
Predicate \ Expression(手动)
<?php
$select->where( new Predicate\Expression( "LOWER(f.foo_name) = 'test'" ) );
//SELECT `f`.* FROM `foo` AS `f` WHERE LOWER(f.foo_name) = 'test'
?>