1

我使用学说 1.2,这是我的架构:

ProviderProduct:
 columns:
   provider_id: 
     type: integer
     primary: true
   product_id:
     type: integer
     primary: true
   num:
     type: integer
     default: 0
     unsigned: true
Provider: 
 columns:
   name: {type: string(255), notnull: true, notblank: true, unique: true}
 relations:
   Products:
     class: Product
     local: provider_id
     foreign: product_id
     refClass: ProviderProduct
Product:
 columns:
    #a lot of columns
 relations:
   Providers:
     class: Provider
     local: product_id
     foreign: provider_id
     refClass: ProviderProduct

我想要的是为特定提供商获得最大数量的产品(这是数量)。我试过这个查询:

$query = Doctrine_Query::create()->select('p.*')
                                     ->from('Product p')
                                     ->innerJoin('p.Providers pr')
                                     ->where('pr.name = ?', 'WhiteStore')
                                     ->orderBy('ProviderProduct.num');
$query->fetchOne();

结果sql查询:

SELECT p.* FROM product p 
INNER JOIN provider_product p3 ON (p.id = p3.product_id) 
INNER JOIN provider p2 ON p2.id = p3.provider_id, provider_product p4 
WHERE (p2.name = ?) ORDER BY p4.num

如您所见,它不是按 num 字段排序的。那么,什么是适合我的任务的 dql?

4

2 回答 2

0

我认为您也需要关联 refClass :

ProviderProduct:
  columns:
    provider_id: 
    type: integer
    primary: true
  product_id:
    type: integer
    primary: true
  num:
    type: integer
    default: 0
    unsigned: true
relations:
  Provider: { foreignAlias: ProviderProduct }
  Product:  { foreignAlias: ProviderProduct }

然后通过 refClass 关联得到数字:

$query = Doctrine_Query::create()->select('p.*')
  ->from('Product p')
  ->innerJoin('p.ProviderProduct pp')
  ->innerJoin('pp.Provider pr')
  ->where('pr.name = ?', 'WhiteStore')
  ->orderBy('pp.num DESC') // to get de max first
  ->groupBy('p.id') // if any duplicates
  ->limit(1);

$product = $query->fetchOne();
于 2016-11-08T15:22:08.440 回答
0

多对多关系如何排序原则查询?

您可以使用以下构造:

$query = Doctrine_Query::create()->select('p.*')
->from('Product p')
->innerJoin('p.Providers pr')
->where('pr.name = ?', 'WhiteStore')
->orderBy('p.Providers.ProviderProduct.num');

Doctrine 1 的非原生行为是为多对多关系创建一个不可见的别名。您可以使用此别名来建立正确的顺序。

于 2016-11-02T10:22:32.703 回答