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

vsaztqbk  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(322)

我有两个表名是杂项和用户。在miscellaneous表中有driver\u id和vendor\u id。在users表中都有name id列。这是我的示例代码。
src/model/table/misscellaneous.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']]);

但什么也看不出来。请帮我找到正确的解决办法。它的工作没有供应商和驱动程序名称的条件。

oug3syen

oug3syen1#

为了 belongTo 关联(蛋糕可以处理普通连接)我经常使用以下代码段:

<?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”作为查找工具,因为我需要列表中的完整记录。。。

相关问题