2015-05-27 55 views
0

这里是我的产品型号:Cakephp3查询模型

$this->table('products'); 
$this->belongsTo('OrderProducts', [ 
    'foreignKey' => 'order_product_id', 
    'propertyName' => 'order_product', 
    'joinType' => 'INNER' 
]); 
$this->hasMany('RefundProducts', [ 
    'foreignKey' => 'product_id', 
    'sort' => ['RefundProducts.created' => 'DESC'], 
    'propertyName' => 'refund_products', 
    'className' => 'RefundProducts' 
]); 

我的查询:

$result = $this->Products->find('all', [ 
    'contain' => [ 
     'RefundProducts' => [ 
      'PriceUnits', 
      'conditions' => $refund_condition, 
     ] 
    ] 
]); 

,但它让所有的产品, 我想唯一的产品有RefundProducts

回答

1

这是工作的matching()方法,这将创建INNER JOIN与RefundProducts,所以你将获得只有Products有一些RefundProducts。在contain限制仅牵强的关联条件

$result = $this->Products->find() 
    ->contain(['RefundProducts' => function ($q) use ($refund_condition) { 
     return $q->where($refund_condition); 
    }]) 
    ->matching('RefundProducts') 
    ->distinct(['Products.id']); 

我不知道什么$refund_condition应该做的。此示例将得到Products,它们有一些RefundProducts,但只有在满足$refund_condition(因此RefundProducts可以返回为空)时才会包含RefundProducts。另外,根据你想要过滤的东西,你可以这样做

->contain(['RefundProducts']) 
->matching('RefundProducts', function ($q) use ($refund_condition) { 
    return $q->where($refund_condition); 
}) 
+0

从 选择 PRODUCT_TYPE,refund_price_unit_id,总和(refund_price) (选择 refund_price_unit_id refund_price_unit_id, (选择 product_type_id 从 产品 其中 ID = a.product_id)PRODUCT_TYPE, refund_price 从 refund_products A)B 按产品类型划分,refund_price_unit_id; 我不知道如何查询CakePHP模型查询 –

+0

@Cao首先,请阅读本指南:** [Query Builder](http://book.cakephp.org/3.0/en/orm/query-builder的.html)**。你可以找到你需要创建的一切,并进一步定制你的查询。 之后,如果您仍然遇到问题以使您的查询正常工作,您可以针对您的特定问题发布另一个问题。 –

1

曹Cường,你有没有试过像这样的关系查询:

$result = Products->find()->contain(['RefundProducts' => function ($q) { 
    return $q 
     ->select(['field1', 'field2']) 
     ->where(['refunded_product' => true])]); 
+0

你试过在cakephp 3吗? – Imran

+0

@imran,请参阅编辑后的答案。 –

0

使用where检查是否使用(RefundProducts在这种情况下)的相关表中的列:

// in your query-object 
$query->where(['Table.column IS NOT NULL']);