Search code examples
databasezend-frameworkormpropel

multiple joined query with propel


Let's consider following tables:

 special_product(
  id
 product_key - FK to product.key)

 product(
 id
 key
 name)

product_attributes(
id
product_id FK to product.id
description
)

My question is how could I write a query that would provide me columns special_product.id, product.id, product_attributes.description starting from the SpecialProductQuery class.

Basically the generated query should be

select s.id, p.id, pa.description 
from special_product s
left join product p on s.key = p.key
left join product_attributes pa on p.id = pa.product_id

Solution

  • Assuming that you've got the relationships build out in your schema you should just be able to do:

     $specialProduct = specialProductQuery::create()
          ->joinWithProduct(SpecialProduct.Product)
          ->joinWith(Product.ProductAttributes)
          ->find();
    

    From here you can get whichever of the values you need from the sub-objects (keep in mind you still need to iterate through the collection):

     foreach($specialProduct as $special)
     {
          $product = $special->getProduct();
     }
    

    YMMV depending on how you've named out your model.