zf many to many relationship, how to find values stored in intermediary table without a second lookup

StackOverflow https://stackoverflow.com/questions/17423285

  •  02-06-2022
  •  | 
  •  

Question

I have a many to many relationship between two tables which is represented with an intermediary table. I am using the ZF1 table relationships methodology to model the database in my application and this works fine. One thing I am struggling with is to pull data from the intermediary table when performing a many to many lookup. For exmaple:

productsTable

product_id, product_name

customerTable

customer_id, customer_name

salesTable

customer_id, product_id, date_of_sale

In this case where the sales table is the intermediary table and the many to many relationship is between customers and products. I add the referenceMap to the sales table model for products and customers and the dependent table "sales" to the product table model and the customer table model.

I can then successfully use the following code to get all the products for a given customer (or vice-versa).

$productTable = new productsTable();
$product = $productTable->find(1)->current();


$customers = $product->findManyToManyRowset('customerTable','salesTable');

But it does not include the "date_of_sale" value in the rowset returned. Is there a way of including the values from the intermediary table without doint a separate database lookup. Ican't see anything in the zf docs.

Any help would be cool. I hope to eventually replace the zend_table with a datamapper implementation as it seems highly inefficient in terms of the number of db queries it executes which could be hugely reduced with slightly more complex SQL join queries rather than multiple simple selects but for now I'm stuck with this.

Thanks.

Was it helpful?

Solution

You can use JOIN queries in your code to make it in one call. From what I understand, you want to build this query

SELECT p.*, c.*, s.date_of_sale FROM sales AS s
INNER JOIN products AS p ON p.product_id = s.product_id
INNER JOIN customers AS c ON c.customer_id = s.customer_id
WHERE p.product_id = '1';

To achieve this, you can refer to Complex SQL query into Zend to see how I translate it to a Zend_Db Query or just use something like

$select = $this->select()->setIntegrityCheck(false);
$select->from(array('s'=>'sales'), array('date_of_sale'));
$select->join(array('p'=>'products'), 'p.product_id = s.product_id', '*');
$select->join(array('c'=>'customers'), 'c.customer_id = s.customer_id', '*');
$select->where('p.product_id = '.$productId);

Obviously, it would be better to quoteInto the where clause but I'm just too lazy.

Hope this helps !

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top