简体   繁体   中英

Best way to create a large dynamic query in Codeigniter?

The scenario is a reporting application. To date, MVC applications I've worked with typically have model methods that respond to one specific question (ie get_username_from_id($id) ). What I'm looking to do is have one query that can respond many different ways depending on checkboxes selected.

So - for example, I may have a query with just one thing in the select or it may have 100 things in the select. The way I've done it, it's gotten messy fast. For example, I wind up doing things like this:

if(in_array("id", $grain)){
    $sql .= "table.id id, ";
}

Is there a best practice for this kind of thing? Or even a way to handle the group by so there isn't a bunch more extra code? I know this is kind of open ended, and I'm probably not even phrasing my question correctly. Much appreciation even to folks who can chime in and help me ask the right question.

I use something like this:

function apply_filters ($filters)
{
        if(isset($filters['user_id']) AND !empty($filters['user_id']))
        {
                $this->db->where('user_id', $filters['user_id']);
        }
}
function get ($filters)
{
        $this->apply_filters($filters);
        return $this->db->get('favourites')->result();
}
function update ($filters, $data)
{
        $this->apply_filters($filters);
        $this->db->update('favourites', $data);
}

You should be able to extend the apply_filters function to your needs. The question is spared alot of details of what you want to do and samples of real data and code, so this is what I can suggest so far.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM