【问题标题】:Array Variable not updated after adding search condition in cakephp 3.437在 cakephp 3.437 中添加搜索条件后,数组变量未更新
【发布时间】:2021-10-13 08:25:23
【问题描述】:

我正在获取分页 $dogs 变量中的数据,然后将其传递给 ctp 并显示该数据。所以当我们来到那个页面时,$dogs 变量有 10 条来自数据库的记录。

当我传递搜索数据并在同一个 $dogs 变量上添加条件时,它会在控制器中使用搜索结果进行更新。例如,如果我在搜索中传递“tomy”并添加条件并更新 $dogs 变量,它只会显示 3 条名为 tomy 的记录。

如果我在控制器中打印 $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。

【问题讨论】:

  • 你可能不得不展示你的一些代码,例如你的控制器动作和视图模板,而没有看到代码中实际发生的事情,所有的人都可以在这里猜测。
  • 我已经编辑了我的问题并添加了该代码。

标签: cakephp cakephp-3.x


【解决方案1】:
// 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]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多