I am trying to build a social network using Zend Framework. However, recently I have difficulty in making some complex SQL queries into Zend language. For example:
"SELECT t.plural_name, p.name as users_name, u.ID
FROM users u, profile p, relationships r, relationship_types t
WHERE t.ID=r.type
AND r.accepted=1
AND (r.usera={$user} OR r.userb={$user})
AND IF( r.usera={$user},u.ID=r.userb,u.ID=r.usera)
AND p.user_id=u.ID"
How could I execute this query using Zend’s select() object? Thank you very much!
Whenever I have complex queries to deal with, I usually try to run them in MySQL. Once I have found the exact SQL statement, I start to ‘translate’ it to Zend. I seems a bit complex but in the long run, you get to do them in Zend right away. Here is how I break it down.
First figure out what the SQL statement is:
Now, you will want to convert all the relationships to joins. The joins are somewhat scary at the beginning but it’s simply a way to put the table and the criteria on which it joins to another table in one line.
Now that it is written in a more ‘Zend friendly’ way, you can easily start to convert it to Zend:
And that should do the job.