Выберите строку с помощью регулярного выражения в Идиорм и Париже

Я ищу следующий эквивалент SQL в Idiorm и Париже:

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

Только после заявлений Idiorm & Paris col=_match_:

Idiorm:

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

Париж:

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

2 ответа

Решение

После прочтения документов и кодов кажется, что 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;
    
    }
    

Предложение 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.

Другие вопросы по тегам