学说1.2:获得相关简单产品有库存的产品

时间:2014-12-28 08:27:55

标签: mysql sql doctrine symfony-1.4 doctrine-1.2

我正在努力研究如何使用Doctrine 1.2生成正确的查询以检索我的产品,其中关联的simple_products的总库存大于1(其中至少有一个库存为1或更多)

我的schema.yml:

Product:
  columns:
    id:
Simple_product:
  columns:
    id:
    quantity:   { type: integer }
    product_id: { type: integer(11), notnull: true }
  relations:
    product_id: { class: Product, local: product_id, foreign: id, foreignAlias: Simple_products }

我试过的示例查询:

$qProducts = Doctrine_Query::create()
  ->select('p.*, SUM(s.quantity)')
  ->from('Product p')
  ->innerJoin('p.Simple_products s')
  ->where('p.category_id = ?', $_SESSION['eshop'],
  ->andWhere('p.brand = ?', $_SESSION['eshop'],
  ->andWhere('p.is_active = 1')
  ->having('SUM(s.quantity) > 0');

此查询未返回预期结果,即使我知道数据库包含带有库存的关联简单产品的产品,也会返回空集合。

我做错了什么?

编辑:

$ qProducts-> getSqlQuery()返回:

SELECT p.id AS p__id, p.sku AS p__sku, p.name AS p__name, p.gender AS p__gender, p.description AS p__description, p.custom_price AS p__custom_price, p.base_price AS p__base_price, p.sales_price AS p__sales_price, p.eshop_price AS p__eshop_price, p.brand AS p__brand, p.product_url AS p__product_url, p.image_url AS p__image_url, p.is_active AS p__is_active, p.category_id AS p__category_id, SUM(s.quantity) AS s__0 FROM product p INNER JOIN simple_product s ON p.id = s.product_id WHERE (p.category_id = ? AND p.brand = ? AND p.is_active = 1) HAVING SUM(s.quantity) > 0

1 个答案:

答案 0 :(得分:1)

我正在寻找的DQL查询:

$qNbProducts = Doctrine_Query::create()
  ->select('p.id')
  ->addSelect('SUM(s.quantity) as sum_stock')
  ->from('Product p')
  ->innerJoin('p.Category c')
  ->leftJoin('p.Simple_products s')
  ->where('c.root_id = ?', $categoryId)
  ->andWhere('p.brand = ?', $_SESSION['eshop'])
  ->andWhere('p.is_active = 1')
  ->groupBy('p.id')
  ->having('sum_stock > 0');