How to check if a record exists in cakephp 2.6?

0

I wonder if a record exists in cakephp 2.6 As everyone knows, cakephp has to use the id key, however this table is a key composed of 4 fields.

I gave a read and tried using beforeSave (), checkUnique and could not get it to work.

  • I'm a beginner, any instruction is welcome.

Thank you in advance for your help.

    
asked by anonymous 24.05.2016 / 16:40

1 answer

0

I needed to check if a registry exists where the key is 4 fields.

I managed to resolve. Here's what I did.

I left this at the end of my model

public function beforeSave($options = array())
{
    $any = $this->find('first', array(
        'conditions' => array(
        'Recibo.funcionario_id' => $this->data['Recibo']['funcionario_id'],
        'Recibo.loja_id' => $this->data['Recibo']['loja_id'],
        'Recibo.ano' => $this->data['Recibo']['ano'],
        'Recibo.mes' => $this->data['Recibo']['mes'])));
    if($any)
    {
        return false;
    }else 
    {
        return true;
    }
}

and left a message on the controller to warn you that it was not included.

if ($this->Recibo->save($this->request->data)) {
                    $recibo_id=$this->Recibo->getInsertId();
                    foreach($this->request->data['ItenRecibo'] as $person) 
                    {
                    //loop for each person added
                        $person['recibo_id']=$recibo_id;
                        $this->Recibo->ItenRecibo->create();
                        $this->Recibo->ItenRecibo->save($person);
                    }//end foreach
                    $this->Session->setFlash('Recibo salvo no BD'); 
                $this->redirect(array('action' => 'index'));                
            }else
            {
                $this->Session->setFlash('Recibo já cadastrado para esse funcionário nesta data!');
            }
    
27.05.2016 / 16:14