【问题标题】:CakePHP: How to use Find method + AJAX request with possibly empty search parametersCakePHP:如何使用可能为空的搜索参数的 Find 方法 + AJAX 请求
【发布时间】:2013-04-11 14:28:21
【问题描述】:

我正在使用 CakePHP v2.3.x,在编辑页面上我需要使用搜索结果动态更新页面...

我正在从我的Views/Tests/admin_edit.php 视图页面之一对我的QuestionsController.php 中的特定操作进行 AJAX 调用。

这是处理请求的操作(到目前为止):

public function admin_search() {
    if ($this->request->is('post')) {
        $searchdata = $this->request->data;
        $r = $this->Question->find('all', array('conditions' => array('Question.id' => $searchdata['id'])));
        echo json_encode($r);
        exit;

    }
}

它目前只返回 ID 与用户输入的问题匹配的问题,但完成的版本将搜索几个不同的字段。我知道如何通过向条件数组添加额外的键/值对来做到这一点。但是,我不知道如何使这些字段成为可选字段。如果用户输入问题名称而不是 id 会怎样,反之亦然?是否有配置使 CakePHP 将忽略任何空字段条件?

同样,有没有办法设置运算符,例如,我可以匹配子字符串或整数范围? 更新:我在文档中找到了this。

【问题讨论】:

    标签: php cakephp cakephp-2.0 cakephp-2.1


    【解决方案1】:

    我会先自己删除所有空条目。

    假设您有一个$searchdata 数组,其中包含三个可选字段,其中一个为空白。首先构建你的条件数组:

    $searchdata = array("id" => 1, "name" => "", "type" => "foo");
    $conditions = array('Question.id' => $searchdata['id'], 'Question.name' => $searchdata['name'], "Question.type" => $searchdata['type']);
    

    (或者如果你想变得花哨)

    foreach($searchdata AS $key => $value) $conditions['Question.' . $key] = $value;
    

    现在清理$conditions,去掉空值:

    $conditions = array_filter($conditions);
    

    多田:

    $r = $this->Question->find('all', array('conditions' => $conditions));
    

    见http://3v4l.org/JN6PA

    【讨论】:

    • 我很喜欢。看起来很干净。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-14
    • 2011-04-07
    • 1970-01-01
    • 2023-03-15
    • 2013-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多