【问题标题】:cakePHP 3.3 cast typeMap in where()cakePHP 3.3 在 where() 中转换 typeMap
【发布时间】:2017-03-17 09:00:46
【问题描述】:

我正在尝试从VARCHAR 类型的表字段customernumber 中获取数据。就是这样,因为客户编号可以是“0024”和“1234”。

$query->getTypeMap() 告诉我它在 cakePHP 中具有 string 类型。现在我们的客户希望在键入“24”或“0024”时获得带有“0024”的客户。

我自己认为没问题,所以我只需将输入值输入到int。但是 cakePHP ORM 似乎根据类型映射进行转换,我不知道如何动态更改类型。

我试过了:

$query->find()
      ->select()
      ->where(['customernumber' => intval($input)]
      ->typeMap(['customernumber' => 'integer']); 

但在我的搜索输入中输入 24 时,我收到一个空结果。

我希望你看到我在寻找什么。谢谢!

【问题讨论】:

  • 不能只用mysql CAST吗?
  • 嗯,你的意思是这样的:$query->find()->select()->where(['customernumber' => $query->func()->cast($input)]->typeMap(['customernumber' => 'integer']); ?可悲的是,我也不会收到结果。
  • no where([$query->func()->cast('customernumber') => $input]) 或类似的东西(我实际上并没有尝试过该代码)

标签: php mysql cakephp orm


【解决方案1】:

谢谢大家,对不起,如果我的问题不是很清楚,但是今天早上我能够找到解决方案,在考虑到您的 cmets 并通过 ORM 回答和调试后,我终于找到了解决方案,这对我有用。

问题是字段 customernumber 被设置为类型“文本”,并且在执行像 customernumber = :comparevalue 这样的比较操作时,:comparevalue 总是被转换为文本。所以我不得不即时将它映射到“整数”,我现在正在这样做:

$query->where(function ($exp) use ($input) {
    return $exp->eq('customernumber', intval($input), 'integer');
})

【讨论】:

    【解决方案2】:

    我会使用 mysql CAST 函数

        $cast = $query->func()->convert([
                'customernumber' => 'identifier',
                'signed' => 'literal'
            ]) ;
    
        $input = '0024';
    
        $query
            ->where(function ($exp) use ($cast, $input) {
            return $exp->eq($cast, intval($input));
        });
    

    这样生成的查询将是

    WHERE (convert((username), signed)) = '23'
    

    【讨论】:

    • 谢谢,正如您所指出的,它将生成 where 查询部分,但我仍然没有得到任何结果。我还尝试直接在 MySQL Workbench 中查询数据库,但也不会得到任何结果。我不知道,但是否可以在 where 子句中以这种方式转换表字段...
    • @ndm:你的想法的问题是,我们的客户过去没有标准化其客户编号,所以可能有像“0042”这样的数字,但也有像“01234”这样的数字”。 ://
    • @Seb 我明白了,从你的问题看来,好像有 4 个字符的限制。
    猜你喜欢
    • 1970-01-01
    • 2023-04-08
    • 2015-07-08
    • 1970-01-01
    • 2021-11-18
    • 2018-06-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多