Cakephp3:如何在带有包含条件的分页中搜索数据?

时间:2018-12-08 10:06:29

标签: php mysql cakephp cakephp-3.0

我有两个表的名称分别是用户和其他。在其他表中有driver_id和vendor_id。用户表中的两个ID均带有名称ID列。这是我的示例代码。

src / Model / Table / Miscellaneous.php

<?php

namespace App\Model\Table;

use Cake\ORM\Table;
use Cake\Validation\Validator;

    class MiscellaneousTable extends Table {

        public function initialize(array $config) {
            $this->table('miscellaneous');
            $this->displayField('name');
            $this->primaryKey('id');

            $this->addBehavior('Timestamp');
            $this->belongsTo('Vendors', [
                'foreignKey' => 'vendor_id',
                'className' => 'users',
                'joinType' => 'left'
            ]);
        $this->belongsTo('Drivers', [
                'foreignKey' => 'driver_id',
                'className' => 'users',
                'joinType' => 'left'
            ]);
        }
    }

我要搜索供应商名称和驱动程序名称。这是我的分娩条件:

if (!empty($this->request->data['vendor']['name'])) {
   $vendor_name = $this->request->data['vendor']['name'];
}
if (!empty($this->request->data['driver']['name'])) {
    $driver_name = $this->request->data['driver']['name'];
}
$miscellaneous = $this->paginate($this->Miscellaneous, ['contain' => ['Drivers' => function(\Cake\ORM\Query $q) {
    return $q->where(['Drivers.name LIKE ' => '%'.$driver_name.'%']);
    }, 'Vendors' => function(\Cake\ORM\Query $q) {
    return $q->where(['Vendors.name LIKE ' => '%'.$vendor_name.'%']);
    }], 'conditions' => $con, 'order' => ['Miscellaneous.id' => 'DESC']]);

但是它什么也没显示。请帮助我找到正确的解决方案。 它的工作不受供应商和驱动程序名称的限制。

1 个答案:

答案 0 :(得分:0)

对于belongTo关联(Cake可以使用普通Joins处理),我经常使用以下代码片段:

<?PHP
  $whereArray = [];
  if (!empty($this->request->data['vendor']['name'])) {
    $whereArray[] = ['Vendors.name LIKE ' => '%'.$this->request->data['vendor']['name'].'%'];
  }
  if (!empty($this->request->data['driver']['name'])) {
    $whereArray[] = ['Drivers.name LIKE ' => '%'.$this->request->data['driver']['name'].'%'];
  }
  $miscellaneous = $this->paginate($this->Miscellaneous->find('all', ['contain' => ['Vendors', 'Drivers']])->where($whereArray)->order(['Miscellaneous.id' => 'DESC']);

?>

注释:我经常使用“ all”作为查找器,因为我也需要列表中的完整记录...