CakePHP:在hasMany关联中查找条件

时间:2015-05-28 15:19:03

标签: php cakephp cakephp-3.0

我正在尝试使用相关模型的条件过滤find()结果。

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

我使用这些模型:

  • 联系人:hasMany('Orders')
  • 订单:belongsTo('Contacts')

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

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

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

  

错误:SQLSTATE [42S22]:找不到列:1054'having子句'中的未知列'Orders'

但是,如何才能使用这些条件只获取已经订购的联系人?

1 个答案:

答案 0 :(得分:0)

我不知道这个解决方案是否最好,但它有效: 通过使用自定义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']);
相关问题