Mysql – How to do a joined query in the ZF tables interface

MySQLzend-db-tablezend-framework

I have the db and my tables look like this:

alt text http://img15.imageshack.us/img15/2568/stackdijag.png

What I want to do is to get all models where manufacturers name column starts with A.
Which means that that simple part of query should be like $manufacturers->fetchAll("name LIKE '$letter%'");

I am trying to accomplish this with ZF relations but it ain't going, so any kind of help is welcome…

Best Answer

$models = new Models();
$select = $models->select(Zend_Db_Table::SELECT_WITH_FROM_PART);
$select->setIntegrityCheck(false)
       ->join(array("a"=>"manufacturers"), 'models.manufacturer_id = a.id',
         array("man_name"=>"name", "man_description"=>"description"))
       ->where("a.name LIKE 'A%'");
$rowset = $models->fetchAll($select);

Unfortunately the Zend_Db_Table relationships interface doesn't have much intelligence in it related to creating joined queries from its declared reference map. The community-contributed solution for complex queries is the Zend_Db_Table_Select query factory.

Note you have to give column aliases for manufacturer's name and description, or else these columns will suppress the model's name and description in the associative array for the row data. You should name columns distinctly to avoid this.

But in your case, I'd skip the table interface and the select interface, and simply execute an SQL query directly using the Db adapter:

$data = $db->fetchAll("
  SELECT m.*, a.name AS man_name, a.description AS man_description
  FROM Models m JOIN Manufacturers a ON m.manufacturer_id = a.id
  WHERE a.name LIKE 'A%'");

You'll get the data back as a simple array of associative arrays, not as a Zend_Db_Table_Rowset. But since a joined rowset isn't writeable anyway, you haven't sacrificed much.