dounie0889 2015-06-06 01:50
浏览 66
已采纳

BETWEEN与范围包括'1'也返回'10'

I'm getting some unexpected behaviour using a BETWEEN predicate in ZF2. Consider the following code:

$ranges = array(
            array(
                'min' => 2,
                'max' => 4
            ),
            array(
                'min' => 7,
                'max' => 9
            )
);

$predicates = array();

foreach($ranges as $range){
    // create a new 'Between' predicate and add it to array
    $between = new Predicate\Between('my_field', $range['min'], $range['max']);
    array_push($predicates, $between);
}

// add predicateset
$select->where->addPredicate(
    new Predicate\PredicateSet(
                            $predicates,
                            Predicate\PredicateSet::COMBINED_BY_OR
                       )
);

Now all of this works fine, except when using a range including 1 (eg. 0-2, 1-5 etc). In that case the resultset also includes values of 10

However, this does not happen when I try something like the query below directy on the DB:

SELECT * FROM my_table WHERE my_field BETWEEN 0 AND 5

(my_field is a varchar in this case)

What am I missing here?

  • 写回答

1条回答 默认 最新

  • duancong7358 2015-06-07 01:36
    关注

    After some digging through the ZF2 libraries, I found out that the Between predicate, always sets the input values to a TYPE_VALUE, which basically means the values get wrapped in quotes.

    One solution would be to change the Between class in the library to use a TYPE_LITERAL, but I think its bad practice to mess around with the ZF2 library.

    In the end I got it to work by setting a custom specification for the predicate, for which ZF2 provides a method setSpecification. This will cast the values back to an integer.

    //...
    
        $between = new Predicate\Between('my_field', $range['min'], $range['max']);
    
        $between->setSpecification('%1$s BETWEEN CAST(%2$s AS UNSIGNED) AND CAST(%3$s AS UNSIGNED)');
    
    //...
    

    Maybe not the prettiest solution, but it works for what I need.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c