Handling Complex WHERE clauses with a PHP Query Builder

后端 未结 5 2146
执念已碎
执念已碎 2021-02-02 01:28

There are several ActiveRecord styled query builder libraries out there. Some are stand alone and some come built into frameworks. However, they really have trouble with WHERE a

5条回答
  •  没有蜡笔的小新
    2021-02-02 02:03

    This is part of my ActiveRecord class, I don't handle sub queries (I don't even bother):

    public function Having($data, $operator = 'LIKE', $merge = 'AND')
    {
        if (array_key_exists('query', $this->sql) === true)
        {
            foreach ($data as $key => $value)
            {
                $this->sql['having'][] = ((empty($this->sql['having']) === true) ? 'HAVING' : $merge) . ' ' . $this->Tick($key) . ' ' . $operator . ' ' . $this->Quote($value);
            }
        }
    
        return $this;
    }
    
    public function Where($data, $operator = 'LIKE', $merge = 'AND')
    {
        if (array_key_exists('query', $this->sql) === true)
        {
            foreach ($data as $key => $value)
            {
                $this->sql['where'][] = ((empty($this->sql['where']) === true) ? 'WHERE' : $merge) . ' ' . $this->Tick($key) . ' ' . $operator . ' ' . $this->Quote($value);
            }
        }
    
        return $this;
    }
    

    One other thing that you may consider is having a customHaving() and customWhere() methods.

提交回复
热议问题