PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, April 22, 2022

[FIXED] How to mix AND OR operators in find conditions CakePHP

 April 22, 2022     cakephp, cakephp-2.3     No comments   

Issue

I want to write this query in CakePHP:

SELECT * FROM pm_management.chk_master_xs_tasks  
    where (eq_model = 'D11 R' OR eq_model = 'TODOS') AND (pm_type = 'XD' OR pm_type = 'XS');

I have tried severals ways like this:

$this->ChkMasterXsTask->find('all', array(
        'conditions' => array('AND' => array(
               array('OR' => array('ChkMasterXsTask.eq_model' => $eq_model,
                                   'ChkMasterXsTask.eq_model' => 'TODOS')),
               array('OR' => array('ChkMasterXsTask.pm_type' => $pm_type,
                                   'ChkMasterXsTask.pm_type' => 'XS'))
                )
            ),     
        ));

But the result is not the expected. Also I saw related questions but doesn't work for me.

Thank you so much for your answers.


Solution

Your problem arises from this code (and this problem is repeated for eq_model)

array('ChkMasterXsTask.pm_type' => $pm_type,
      'ChkMasterXsTask.pm_type' => 'XS')

which tries to assign 2 values to the same key of that associative array. You could rewrite your code to this:

array(array('ChkMasterXsTask.pm_type' => $pm_type),
      array('ChkMasterXsTask.pm_type' => 'XS'))

Another option which improves readability, uses SQL's IN function. The equivalent SQL becomes

SELECT * 
FROM pm_management.chk_master_xs_tasks  
WHERE eq_model IN ('D11 R', 'TODOS') 
  AND pm_type IN ('XD', 'XS');

Which should make your find a little easier write:

$this->ChkMasterXsTask->find('all', array(
        'conditions' => array(
          'ChkMasterXsTask.eq_model' => array($eq_model, 'TODOS'),
          'ChkMasterXsTask.pm_type' => array($pm_type, 'XS'))
        ));


Answered By - AgRizzo
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing