在cakephp 3.437中添加搜索条件后未更新数组变量

rks48beu  于 2022-11-11  发布在  PHP
关注(0)|答案(1)|浏览(119)

我在pagination $dogs变量中提取数据,然后将其传递到ctp并显示这些数据。因此,当我们来到该页面时,$dogs变量有10条来自数据库的记录。
当我传递搜索数据并在同一个$dogs变量上添加条件时,它会在控制器中使用搜索结果进行更新。例如,如果我在搜索中传递“toms”并添加条件和更新$dogs变量,它只会显示3条名为toms的记录。
如果我在控制器中打印$dogs变量,它会给予我3个记录的正确结果。
但是在ctp文件上,它显示的数据没有添加条件,即默认的结果,我第一次提取时,我们加载的页面是10条记录。
我也清除了缓存,但不确定为什么会发生这种情况。
下面是我的代码

if ($this->request->is('post')) {

$data = $this->request->getData();
$dogname = $data['search_dog'];
$id = $data['client_id'];
$this->request->session()->write('search_dog', $dogname);
//$conditions['name LIKE'] = "%" . $dogname . "%";

$this->ClientDogs->belongsTo('ClientUsers', [
    'className' => 'ClientUsers',
    'foreignKey' => 'client_users_id',
]);

$dogs = $this->paginate($this->ClientDogs->find('all', ['contain' => ['ClientUsers'], 'conditions' => array('name LIKE' => '%' . $dogname . '%')]), ['limit' => 9]);

}否则{

$this->ClientDogs->belongsTo('ClientUsers', [
    'className' => 'ClientUsers',
    'foreignKey' => 'client_users_id',
]);

$dogs = $this->paginate($this->ClientDogs->find('all', ['contain' => ['ClientUsers']]), ['limit' => 9]);

}
这里$dogs变量在控制器中给出了正确的结果,但是当我在ctp文件中传递$dogs变量时,它给出了相同的结果,无论我传递什么条件,都提取了所有$dogs。

wfypjpf4

wfypjpf41#

// keep this inside ClientDogs Model
$this->belongsTo('ClientUsers', [
    'className' => 'ClientUsers',
    'foreignKey' => 'client_users_id',
]);

// Inside controller

// why to use POST while search ?
// if the filters params sent via post it wont be on the URL, and it cant be retrive while GET
// if the $dogname is stored on the session, it has to retrive while GET

$params = $this->request->getQuery();

// $id = $params['client_id']; // this is unused

$conditions = [];
if(!empty($params['search_dog'])){
    $conditions[] = ['ClientDogs.name LIKE' => '%' . $params['search_dog'] . '%'];
}

$dogQuery = $this->ClientDogs->find('all', ['contain' => ['ClientUsers'], 'conditions' => $conditions ]);

$dogs = $this->paginate($dogQuery, ['limit' => 9]);

相关问题