通过分页查找相关数据

问题描述 投票:0回答:2

我有两个:ProvidersPurchasetopay具有以下关联:

$Providers->hasMany('Purchasetopay', [
   'foreignKey' => 'providers_id'
]);

而且我还有以下操作:

public function fornecedores(){

        $Providers = TableRegistry::get('Providers');

        $pesquisar = $this->request->query('pesquisar');

        if(!empty($pesquisar)){
            $this->paginate = [
                'conditions' => 
                            [ 'OR' => 
                                ['Providers.cnpj' => $pesquisar,
                                 'Providers.corporatename LIKE' => '%'.$pesquisar.'%',
                                ]                              
                            ]
                         ];
        }

        $query = $Providers->find()->contain(['Telephones','Purchasetopay'=>['SupplierNotes']]);
        $providers = $this->paginate($query);
        $this->set(compact('providers'));

    }

我需要将Purchasetopay字段添加到OR条件。怎么样?我看到了以下解决方案:https://stackoverflow.com/a/39559315/11239369但是,我不知道如何修改我的代码以这种方式工作。

cakephp cakephp-3.0 model-associations
2个回答
0
投票

您可以使用orWhere / andWhere,如下所示:

$query = $Providers->find()
          ->contain(['Telephones','Purchasetopay'=>['SupplierNotes']])
          ->where( ['Providers.cnpj' => $pesquisar])
          ->orWhere(['Providers.corporatename LIKE' => '%'.$pesquisar.'%' ]);

0
投票

您可以尝试以下操作

    $pesquisar = $this->request->query('pesquisar');

    $condition = [];
    if(!empty($key))
    {
        $condition[] = [
                        'OR' => [['Providers.cnpj LIKE'=>'%'.$pesquisar.'%'], ['Providers.corporatename LIKE'=>'%'.$pesquisar.'%']],
        ];
    }

    $query = $this ->Providers
                    ->find()
                    ->contain(['Telephones','Purchasetopay'=>['SupplierNotes']])
                    ->where($condition);

    $providers= $this->paginate($query);  // pagination to get all data with association.
© www.soinside.com 2019 - 2024. All rights reserved.