CakePHP :根据 hasMany 关联查找条件

CakePHP : find with conditions on hasMany association

我正在尝试根据关联模型的条件过滤 find() 结果。

我找到了适用于 CakePHP 2.x 的解决方案,但我正在使用 CakePHP 3.x。

我使用这些模型:

在我的 ContactsController 中,我想显示仅具有一个或多个订单的联系人

public function customers() {
    $this->paginate = [
        'contain' => ['Orders'],
        'having' => ['Orders']
    ];
    $contacts = $this->paginate($this->Contacts);
    $this->set('contacts', $contacts);
}

当然,它不起作用,因为 CakePHP 不使用具有 'hasMany' 关联的连接,我收到此错误:

Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Orders' in 'having clause'

但是我如何使用条件来仅获取已经订购的联系人?

我不知道这个解决方案是否最好,但它有效: 通过使用自定义 join,您可以按联系人统计订单数量,然后在 count_orders.

上使用 having
    $contacts = $this->Contacts->find('all', [
        'fields' => [
            'contact_id' => 'Contacts.contact_id',
            // Others fields you need
            'count_orders' => 'COUNT(order_id)'
        ],
        'join' => [
            'table' => 'orders', 
            'type' => 'LEFT', 
            'conditions' => 'orders.contact_id = Contacts.contact_id'
        ],
        'group' => ['Contacts.contact_id'],
        'having' => ['count_orders > 0'] // Remove contacts without orders
    ]);
    $this->set('contacts', $contacts);
    $this->set('_serialize', ['contacts']);