0

我有一个带有许多屏幕的 CakePHP 应用程序,它使用来自特定模型的数据。大多数时候,我需要检查一个特定的字段(如说明书中的“user_active=>1”示例),但是我仍然希望能够将该字段指定为条件并覆盖默认值。我的代码有效,但这是最好的方法吗?

此外,$queryData 字段是混合的——除了数组之外还有哪些可能性?只是空?

<?php public function beforeFind($queryData) {
    if(is_array($queryData)) {
        //query data was an array
        if(!is_array($queryData['conditions'])) {
            $queryData['conditions'] = array('Course.semester_id'=>SEMESTER_ID);
        } else if (!isset($queryData['conditions']['Course.semester_id'])) {
            $queryData['conditions']['Course.semester_id'] = SEMESTER_ID;
        }
    }
} ?>
4

1 回答 1

0

我建议findCourses($options)在您的模型中创建一个自定义函数。这样,您只需设置所有默认条件,并覆盖任何传入的$options.

这是一个例子:

//Article model

public function articles($opts = null) {

    //initialize
    $params = array();
    $findType = 'all';
    $params['conditions'] = array();

    //status
    if(!empty($opts['status'])) {
        array_push($params['conditions'], array('Article.status'=>$opts['status']));
    } else {
        array_push($params['conditions'], array('Article.status'=>1));
    }

    //id
    if(!empty($opts['id'])) {
        $params['limit'] = 1;
        $findType = 'first';
        array_push($params['conditions'], array('Article.id'=>$opts['id']));
    }

    //slug
    if(!empty($opts['slug'])) {
        $params['limit'] = 1;
        $findType = 'first';
        array_push($params['conditions'], array('Article.slug'=>$opts['slug']));
    }

    //limit (and find type)
    if(!empty($opts['limit'])) {
        $params['limit'] = $opts['limit'];
        if($opts['limit'] == 1) $findType = 'first';
    }

    //order by
    $params['order'] = array('Article.created DESC');
    if(!empty($opts['order'])) {
        $params['order'] = $opts['order'];
    }

    //type
    if(!empty($opts['type'])) {
        array_push($params['conditions'], array('type'=>$opts['type']));
    }

    //find type
    if(!empty($opts['find_type'])) $findType = $opts['find_type'];

    //slug
    if(!empty($opts['slug'])) {
        array_push($params['conditions'], array('slug'=>$opts['slug']));
    }

    //search
    if(!empty($opts['search'])) {
        array_push($params['conditions'], array('Article.title LIKE' => '%'.$opts['search'].'%'));
    }

    //contain
    $params['contain'] = array('MetaData', 'Tag', 'Upload');

    //paginate options or results
    if(!empty($opts['paginate'])) {
        return $params;
    } else {
        return $this->find($findType, $params);
    }

}

在我的控制器中,我可以这样做:

$opts = array('limit'=>6, 'type'=>'gaming');
$articles = $this->Article->articles($opts);
于 2012-07-19T15:48:54.297 回答