views:

48

answers:

3

Is there a best practice in getting data from multiple database tables using Zend? I would like to know rather than end up wanting to refactor the code I write in the near future. I was reading the Zend documentation and it said that:

"You can not specify columns from a JOINed tabled to be returned in a row/rowset. Doing so will trigger a PHP error. This was done to ensure the integrity of the Zend_Db_Table is retained. i.e. A Zend_Db_Table_Row should only reference columns derived from its parent table."

I assume I therefore need to use multiple models -- is that correct? If, for example, I want to get out all orders for a particular user id where the date is in between two dates what would I do?

I know that it would be possible to access the two different models from a controller and then combine their respective data in the action but I would not feel happy doing this since I have been reading survivethedeepend.com and it tells me that I shouldn't do this...

Where, why, and how? :)

Thanks!

+2  A: 

If you're reading ZFSTDE, in chapter 9 (http://www.survivethedeepend.com/zendframeworkbook/en/1.0/implementing.the.domain.model.entries.and.authors) this problem is addressed by using a data mapper.

Also, you can join 2 tables, just be sure to first call on the select object the setIntegrityCheck(false) method. The docs say that a row should reference a parent table, doesn't mean it can not :)

robertbasic
+1  A: 

Stop thinking about Zend_Db_Table as your "model".

You should write your own, rich, domain-centric model classes to sit between your controllers (and views), and your persistence logic (anything that uses Zend_Db/Zend_Db_Table/Zend_Db_Select) to load/store data from the database.

timdev
Are you suggesting that the model would access further classes that are extended from Zend_Db_Table_Abstract?
lhnz
@Ihnz no, he's suggesting that the Model is your application, while your Controllers and Views are just an interface to it.
Gordon
@lhnz - actually, yes, but everything else Gordon just said is true too. You might have some persistence/data-mapper classes that your more domain-centric model classes use, but your model should be *more* than just a database abstraction. If you find yourself using classes that extend Zend_Db_anything directly in your controllers, that's a big red flag that you need to create a richer model.
timdev
+1  A: 

Sure, you can query several db tables at the same time. Take a look at the official ZF docs here http://framework.zend.com/manual/en/zend.db.select.html#zend.db.select.building.join

As for your example with getting all orders of a single user, table relationships are the answer http://framework.zend.com/manual/en/zend.db.table.relationships.html

Vika