Good day to all
Zend Framework fans. I think that many of you know, love and use the
Zend_Db_Select class to build sql queries. Undoubtedly, this approach has a lot of advantages. It is enough to study the
documentation in order to easily write the simplest queries to the database. But what if the required requests are not entirely simple?
On Habré
were already posts for solving this kind of problems. But recently I faced the task of writing the following query:
SELECT * FROM `table` WHERE `sex`= "male" AND (`age` > 18 OR `hobby` = "sport");
It seems to be nothing complicated, the first thing that comes to mind is the use of the
orWhere method:
$this->select() ->where( "sex = ?", "male" ) ->where( "age > ?", 18, "INTEGER" ) ->orWhere( "hobby = ?", "sport" );
But this will generate the following SQL code:
SELECT `table`.* FROM `table` WHERE (`table`.`sex`= "male") AND (`table`.`age` > 18) OR (`table`.`hobby` = "sport");
That is not the request that we expect to send to the database. How to be? I propose this solution:
$select = $this->select(); $condition = $select->orWhere( "age > ?", 18, "INTEGER" ) ->orWhere( "hobby = ?", "sport" ) ->getPart( Zend_Db_Select::WHERE ); $condition = is_array( $condition ) ? implode( " ", $condition ) : $condition; $select->reset( Zend_Db_Select::WHERE ); $select->where( "sex = ?", "male" ) ->where( $condition );
As a result, we have an absolutely correct request. All successful coding;)