在CakePHP 3中按条件查找关联模型 [英] Find by conditions on associated model in CakePHP 3

查看:81
本文介绍了在CakePHP 3中按条件查找关联模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个表 orders sub_orders
他们的关联是

I have two tables orders and sub_orders. Their association is

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

两个表都有 invoice_no 和<$ c分别在订单子订单的$ c> sub_invoice 列中。

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

我必须从 orders 表中查找包含相关的 sub_orders 的记录,其中 $ trackingId 将匹配 Orders.invoice_no SubOrders.sub_invoice

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

但这会产生错误

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


推荐答案

尝试执行以下查询:

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

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

这篇关于在CakePHP 3中按条件查找关联模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆