我正在尝试使用教义的 DQL 加入自己的表。场景是:
我有一个产品属性值表,它通过参考表链接到产品表。产品属性值将用作产品的过滤器,因此,产品属性值表需要连接回自身以过滤多个属性。
我的方法如下:
public static function getProductsByCategoryCode($productCategoryCode, $currencyCode, Zend_Session_Namespace $filters = null)
{
$products = Doctrine_Query::create()
->from('Products p')
->leftJoin('p.ProductCategories pc')
->leftJoin('p.ProductPrices pp')
->leftJoin('pp.Currencies c')
->where('pc.product_category_code = '. $productCategoryCode)
->addWhere('c.currency_code = "'. $currencyCode . '"');
if($filters !== null)
{
$i = 0;
foreach($filters as $index => $value)
{
$alias = 'pav_' . (string)$i;
$products
->leftJoin('p.ProductAttributeValues ' . $alias)
->addWhere($alias . '.product_attribute_code = "'. $index . '"')
->addWhere($alias . '.value = "'. $value . '"');
$i++;
}
}
die($products->getSql());
return $products->execute();
}
问题是从getSql()
调用中获得的结果 SQL 对产品属性值链接表有重复的别名(MySQL 错误:)#1066 - Not unique table/alias: 'p6'
。据推测,这是由于产品和产品属性值之间的引用关系(产品属性值链接)被重用。
生成的 SQL 为:
SELECT
p.product_code AS p__product_code,
p.name AS p__name,
p.description AS p__description,
p2.product_category_code AS p2__product_category_code,
p2.name AS p2__name,
p2.category_route AS p2__category_route,
p2.parent_product_category_code AS p2__parent_product_category_code,
p2.lft AS p2__lft,
p2.rgt AS p2__rgt,
p2.level AS p2__level,
p4.currency_code AS p4__currency_code,
p4.product_code AS p4__product_code,
p4.net_value AS p4__net_value,
c.currency_code AS c__currency_code,
p5.product_attribute_value_id AS p5__product_attribute_value_id,
p5.product_attribute_code AS p5__product_attribute_code,
p5.value AS p5__value,
p7.product_attribute_value_id AS p7__product_attribute_value_id,
p7.product_attribute_code AS p7__product_attribute_code,
p7.value AS p7__value
FROM
products p
LEFT JOIN
product_category_links p3 ON p.product_code = p3.product_code
LEFT JOIN
product_categories p2 ON p2.product_category_code = p3.product_category_code
LEFT JOIN
product_prices p4 ON p.product_code = p4.product_code
LEFT JOIN
currencies c ON p4.currency_code = c.currency_code
LEFT JOIN
product_attribute_value_links p6 ON p.product_code = p6.product_code
LEFT JOIN
product_attribute_values p5 ON
p5.product_attribute_value_id = p6.product_attribute_value_id
LEFT JOIN
product_attribute_value_links p6 ON p.product_code = p6.product_code
LEFT JOIN
product_attribute_values p7 ON
p7.product_attribute_value_id = p6.product_attribute_value_id
WHERE
p2.product_category_code = 10100
AND
c.currency_code = "GBP"
AND
p5.product_attribute_code = "BRAND"
AND
p5.value = "Advanced Hair Gear"
AND
p7.product_attribute_code = "SIZE" AND p7.value = "238 ml"
如您所见,P6 作为别名出现了两次。
有人知道使用 DQL 实现此目的的正确方法吗?
提前谢谢了。