使用多态过滤MySQL结果

时间:2014-11-14 20:57:15

标签: php mysql sql polymorphism

我在报告'中设置了方法。根据日期输入获取结果的类,例如:

public function total_things_to_date() {

    return mysqli_num_rows($this -> db -> blank_query(" SELECT `thing_id`
                                                        FROM `things`
                                                        WHERE `client_id` = '{$_SESSION['client_id']}'
                                                        AND `thatid` IN (" . $this -> db -> prepareInClause($this -> that_id_array) . ")"));

}

我正在寻找关于如何在不必重写方法的情况下为此查询添加过滤器的想法......例如,如果我要按department_id过滤并且我必须重写方法我可以附加一个AND条款:

public function total_things_to_date() {

    return mysqli_num_rows($this -> db -> blank_query(" SELECT `thing_id`
                                                        FROM `things`
                                                        WHERE `client_id` = '{$_SESSION['client_id']}'
                                                        AND `thatid` IN (" . $this -> db -> prepareInClause($this -> that_id_array) . ")
                                                        AND `deptid` = '$deptid'"));

}

或者,我可以解析方法的参数来过滤结果:

public function total_things_to_date($where = NULL, $selector = NULL) {

    if($where != NULL && $selector != NULL) {

        return mysqli_num_rows($this -> db -> blank_query(" SELECT `thing_id`
                                                            FROM `things`
                                                            WHERE `client_id` = '{$_SESSION['client_id']}'
                                                            AND `thatid` IN (" . $this -> db -> prepareInClause($this -> that_id_array) . ")
                                                            AND `deptid` = '$deptid'"));

    } else {

        //some array checks etc.

        $filterString = "";
        for($i=0;$i<count($where); $i++) {
            $filterString .= "AND `$where[$i]` = '$selector[$i]'";
        }

        return mysqli_num_rows($this -> db -> blank_query(" SELECT `thing_id`
                                                            FROM `things`
                                                            WHERE `client_id` = '{$_SESSION['client_id']}'
                                                            AND `thatid` IN (" . $this -> db -> prepareInClause($this -> that_id_array) . ")
                                                            $filterString"));

    }

}

这样可以正常工作但是有一种不那么难看的方式/是否有一个首选的方法呢?

1 个答案:

答案 0 :(得分:1)

您可以将数据作为字符串数组传递:

$conditions = array("`dept_id`=1","`some_id`=2");

public function total_things_to_date( $conditions ) 
{
    $query = "SELECT `thing_id`
             FROM `things`
             WHERE `client_id` = '{$_SESSION['client_id']}'
             AND `thatid` IN (" . $this -> db -> prepareInClause($this -> that_id_array) . ")";
    $query .= implode( "AND", $conditions );
    return mysqli_num_rows($this -> db -> blank_query( $query );
}

同样的事情,但有点清洁。