Query brings data ignoring $conditions

Asked

Viewed 52 times

1

I’m making a query and the cake is bringing all the data ignoring $conditions. I want to search by date, but when I put a date that does not exist in any record, it still brings all the data.

public function consultarDespesa() {
    if ($this->request->is('post')) {

        $dataDespesa=null;

        $dataDespesa = $this->request->data['Despesa']['ano']."-".$this->request->data['Despesa']['mes'];

        $despesas = $this->Despesa->find('all', array(
'conditions'=>array(
    'data_despesa like'=>"%$this->dataDespesa%")));

        if (($despesas==null) || (!isset($despesas))) {
            $this->Session->setFlash("Sua pesquisa não retornou nenhum resultado.");
        }

        else {
            $this->Session->write("Despesas", $despesas);

            $this->redirect(array('action'=>'exibirDespesas'));
        }
    }
}

http://www.hastebin.com/aluridixiq.coffee

2 answers

1

Change this:

'data_despesa like'=>"%$this->dataDespesa%"

for:

"data_despesa like '%{$this->dataDespesa}%'"

1


You’re comparing date to date LIKE, in which case no record will return to you, as no record is equal to the date you are seeking.

When buying a date of a particular day you can use >= and <=, between or other ways of comparing dates.

I did it with bigger and equal

$despesas = $this->Despesa->find('all', array(
    'conditions'=>array(
        'data_despesa >='=>"%$this->dataDespesa%",
        'data_despesa <='=>"%$this->dataDespesa%"
        )   
    ));

Edit - Try to compare this way:

$despesas = $this->Despesa->find('all', array(
    'conditions'=>array(
        'MONTH(data_despesa)'=>$this->request->data['Despesa']['mes'],
        'YEAR(data_despesa)'=>$this->request->data['Despesa']['ano']
        )   
    ));
  • True, but it depends on how the date is recorded in the bank.

  • @Jeferson Assis I’m using like because I just want to take as argument the month and the year, the day does not interest me. The like works, because I did with query and only brought when found. And in the conversion of cake, is ignoring the operator, bringing everything as if it were a select *

  • I changed the answer and put a complement, try the second way

  • @Andrénascimento This date is in your database as DATETIME or VARCHAR?

  • !Jeferson Assis worked!

Browser other questions tagged

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