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

Asked

Viewed 234 times

1

select count(situacao) as Qtde, sum(valorcausa) as Total_Valor_Causa 
from processo
where situacao = "Tramitando";

1 answer

1

There are several ways to do this, the one I recommend, for making 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 the query(), thus:

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

I recommend the first one because you can add other filters in the query, such as:

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

The above code will add an order by Total_Valor_Causa.

To return only one line, you can sort by id desc, and limit the query to 1 record, so the result will be the last record inserted;

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

More information

  • Thank you very much Dobrychtop, excellent reply.

  • Would you like to tell me how to display only the last row of a table, in a query written in the model class? thanks

  • @Ramiro, I added the answer a way to do this.

  • Thanks again @Dobrychtop, it worked, the problem is that I am not able to do what I need, which is to generate a report that involves two tables, (A and B), being: Table A composed by (codprocesso, nprocesso), and Table B inherits from A possessing the compos (codandamento, Descricao, fkcodprocesso). What I need to do in the Model class is to list all the processes, and the last progress of each 1 (one) of the existing processes. Would you have an idea how to do that? Thanks again!

  • I always try to make the sql pure first and then pass to CI, so the query: select nprocess, codandamento, dtandamento, Descricao from processo INNER JOIN andamento ON andamento.fkcodprocesso = processo.codprocess order by codandamento desc limit 1; I already passed to CI, this query, however it returns me only one record, which is the last of the table progress, being what I want to display, is the last record of each fkcodprocess (forein key) in the table progress. Got it?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.