Sunday, January 16, 2022

[FIXED] Find by conditions on associated model in CakePHP 3

Issue

I have two tables orders and sub_orders. Their association is

$orders->hasMany('SubOrders', [
   'foreignKey' => 'order_id'
]);

Both tables have invoice_no and sub_invoice columns in orders and sub_orders respectively.

I have to find records from orders table containing associated sub_orders where $trackingId will match either Orders.invoice_no or SubOrders.sub_invoice

$findOrder = $this->Orders->find('all', [
    'conditions' => [
      'OR' => [
         'Orders.invoice_no' => $trackingId,
         'SubOrders.sub_invoice' => $trackingId
       ]
     ],
     'contain' => [
        'SubOrders'
     ]
  ]);

But this gives error

Column not found: 1054 Unknown column 'SubOrders.sub_invoice' in 'where clause'

Solution

Try doing the query like this:

$findOrder = $this->Orders->find()
->where(['Orders.invoice_no' => $trackingId])
->contain(['SubOrders' => function ($q) use ($trackingId) {
   return $q

        ->where(['SubOrders.sub_invoice' => $trackingId]);
}
]);


Answered By - Derek

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.