【问题标题】:Select row by regex match in Idiorm and Paris在 Idiorm 和 Paris 中按正则表达式匹配选择行
【发布时间】:2015-09-04 13:42:05
【问题描述】:

我正在 Idiorm 和 Paris 中寻找以下 SQL 等效项:

SELECT * FROM table WHERE (regex=0 AND col=_match_) OR (regex=1 AND _match_ REGEXP col)
LIMIT 1

Following Idiorm & Paris statements 仅匹配 col=_match_:

成语:

$row = ORM::for_table('table')
->where_equal('col', '_match_')
->find_one()

巴黎:

MyModel::where('col', '_match_')->find_one()

【问题讨论】:

    标签: php model idiorm


    【解决方案1】:

    句子 where_any 是解决这个问题的方法 示例:

    $myModel = ORM::for_table('table')
            ->where_any_is(array(
                array('regex'=> 0,'col' => 'match'),
                array('regex'=> 1,'col' => '_match_')))
            ->limit(1)->find_many();
    

    过滤查询见官方文档:https://idiorm.readthedocs.org/en/latest/querying.html#filtering-results

    【讨论】:

    • 谢谢牧师的代码,真的很有用。但我希望在正则表达式列等于 1 的行上匹配为正则表达式。
    【解决方案2】:

    阅读文档和代码后,Idiorm/Paris 似乎不支持该功能。所以,我们有两个选择:

    1. 使用where_raw()方法,通过这种方式我们将where子句作为字符串直接传递给Idiorm。

    2. where_condition() 之类的新方法添加到 Idiorm ORM 类,通过设置 $reverse = true 将 $value 与 $column_name 匹配,否则,这是一个正常的 where 条件(匹配 $column_name 与 $value)。

      public function where_condition($column_name, $operator, $value, $reverse = false)
      {
      $multiple = is_array($column_name) ? $column_name : array($column_name => $value);
      $result = $this;
      
      foreach($multiple as $key => $val) {
          // Add the table name in case of ambiguous columns
          if (count($result->_join_sources) > 0 && strpos($key, '.') === false) {
              $table = $result->_table_name;
              if (!is_null($result->_table_alias)) {
                  $table = $result->_table_alias;
              }
      
              $key = "{$table}.{$key}";
          }
          $key = $result->_quote_identifier($key);
      
          if($reverse)
              $result = $result->_add_condition('where', "? {$operator} {$key}", $val);
          else
             $result = $result->_add_condition('where', "{$key} {$operator} ?", $val); 
      }
      return $result;
      
      }
      

    【讨论】:

      猜你喜欢
      • 2016-09-28
      • 1970-01-01
      • 1970-01-01
      • 2018-07-29
      • 2016-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      相关资源
      最近更新 更多