0

Here is my Product Model:

$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'
]);

My query:

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

but it get all product, i want to get only product have RefundProducts

3 Answers 3

1

This is job for matching() method, which will create INNER JOIN with RefundProducts, so you will get only Products that have some RefundProducts. Conditions in contain limit only fetched associations

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

I'm not sure what $refund_condition should do. This example will get Products that have some RefundProducts, but will contain RefundProducts only if $refund_condition is satisfied (so RefundProducts can get back as empty). Alternatively, based on what you want to filter, you can do it this way

->contain(['RefundProducts'])
->matching('RefundProducts', function ($q) use ($refund_condition) {
    return $q->where($refund_condition);
})
Sign up to request clarification or add additional context in comments.

2 Comments

select product_type, refund_price_unit_id, sum(refund_price) from (select refund_price_unit_id refund_price_unit_id, (select product_type_id from products where id = a.product_id) product_type, refund_price from refund_products a) b group by product_type , refund_price_unit_id; i don't know how to query In Cakephp Model query
@Cao First, please read this guide: Query Builder. You can find there everything you need to create and further customize your queries. After that, if you will be still having problems to make your queries work, you can post another question with your specific problem.
1

Cao Thế Cường, have you tried relational query like this:

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

Comments

0

Use a where to check if a column of the related table (RefundProducts in this case) is used:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.