代码点火器 3:到目前为止,查询生成器中是否添加了任何'where'条件?



我正在使用codeigniter 3.我只需要知道是否有一个''''条件添加到查询构建器中。

我正在调用一个"删除"函数,该函数从数据库中删除行,并且可以在调用该函数之前添加一个条件。这样的东西:

public function delete()
{
    // Here I need to know if where condition added to the db class
    $this->db
        ->where('field', 1)
        ->delete('my_table');
}
public function main()
{
    $this->db->where('field2', 2);
    $this->delete();
} 

在控制器

function delete_row()
{
   $this->load->model('model_name');
   // Pass the id or something else to the row_delete() method
   $this->model_name->row_delete($id);
}

在模型

function row_delete($id)
{
   $this->db->where('id', $id);
   $this->db->delete('table_name'); 
}

根据您的示例:

public function delete_method($condition,$table_name )
{
    $this->db->where($condition)
    $this->db->delete($table_name);
}
public function main()
{
   $condition = [
     'field1'=>1,
     'field2'=>2
   ];
   $table_name = 'my_table';
   $this->delete_method($condition,$table_name );
} 

我找到了一个解决方案。我唯一需要做的就是获取选择查询并搜索其中的" Where"子句:

public function delete()
{
    // Here I need to know if where condition added to the db class
    $sql = $this->db->get_compiled_select(NULL, FALSE);
    $has_where = stripos($sql, 'where') !== FALSE;
    // $has_where is TRUE if there is a where condition defined until now
    $this->db
        ->where('field', 1)
        ->delete('my_table');
}
public function main()
{
    $this->db->where('field2', 2);
    $this->delete();
} 

最新更新