Find by conditions on associated model in CakePHP 3

烂漫一生 提交于 2019-12-21 19:59:15

问题


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'

回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!