通过正则表达式匹配在Idiorm和Paris中选择行


Select row by regex match in Idiorm and Paris

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

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

后文&Paris语句只匹配col=_match_:

Idiorm:

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

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

句子中_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

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

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

  2. 添加一个新的方法,如where_condition()到Idiorm ORM类匹配$value对$column_name通过设置$reverse = true,否则,它是一个正常的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;
    }