How do I write the following SQL code in the Codeigniter Model?

1
select count(situacao) as Qtde, sum(valorcausa) as Total_Valor_Causa 
from processo
where situacao = "Tramitando";
    
asked by anonymous 23.04.2018 / 22:58

1 answer

1

There are several ways to do this, which I recommend, for leaving the code more organized is this:

$this->db->select('count(situacao) as Qtde, sum(valorcausa) as Total_Valor_Causa');
$this->db->where('situacao', 'Tramitando');
$query = $this->db->get('processo');

Another way is to put the entire query inside query() , like this:

$this->db->query('select count(situacao) as Qtde, sum(valorcausa) as Total_Valor_Causa 
from processo where situacao = "Tramitando"')->get();

I recommend the first because you can add other filters in the query, like:

$this->db->order_by('Total_Valor_Causa', 'DESC');

The above code will add a sort by Total_Valor_Causa .

To return only one row, you can sort by id desc , and limit the query to 1 record, thus the result will be the last record entered;

$this->db->order_by('id', 'DESC');
$this->db->limit(1);

More Information

    
24.04.2018 / 18:46