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'
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]);
}
]);
来源:https://stackoverflow.com/questions/39558115/find-by-conditions-on-associated-model-in-cakephp-3