E
E
exaller2014-01-20 04:36:45
CakePHP
exaller, 2014-01-20 04:36:45

SQL Many to Many selection with AND condition in CakePHP

Given:
table users:
id | name
table users_problems:
id | user_id | problem_id
table problems:
id | name
Required:
Make a selection of users who will have a problem with id = 1 & (and) id = 2 at the same time. If you are not familiar with CakePHP, write at least a variant of the SQL query.
My variation but it works like id = 1 || (or) id = 2:

$conditions = array(				
  'conditions' => array(
    'UsersProblem.problem_id' => array(1, 2)
    ),
  'recursive' => -1,
  );
$conditions['joins'][] = array(
  'table' => 'users_problems',
  'alias' => 'UsersProblem',
  'type' => 'INNER',
  'conditions' => array(
    'User.id = UsersProblem.user_id',
  ));

This option doesn't work:
$conditions = array(	
        'fields' => array(
          'User.id'
          ),		
        'conditions' => array(
          'AND' => array(
            'UsersProblem.problem_id' => 38,
            'UsersProblem.problem_id' => 41,
            )					
 					),
        'recursive' => -1,
        'contain' => array(
          'Problem'
          )
        );

      $conditions['joins'][] = array(
        'table' => 'users_problems',
        'alias' => 'UsersProblem',
        'type' => 'INNER',
        'conditions' => array(
          'User.id = UsersProblem.user_id',
        ));

Doesn't work because it takes only the last value from AND. This results in a query like this:
SELECT `User`.`id` FROM `lawyers`.`users` AS `User` INNER JOIN `lawyers`.`users_problems` AS `UsersProblem` ON (`User`.`id` = `UsersProblem`.`user_id`) WHERE `UsersProblem`.`problem_id` = 41

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Marat Dallin, 2014-01-23
@amr-dallin

Hello. At first, you not correctly adjusted associations. Secondly, I do not advise you to climb into JOIN. This puts a lot of pressure on the system and you may regret it in the future when working with CakePHP. In general, I wrote a script. He fulfills your requirements. If you need the right associations or have other questions, then write to skype amr.dallin.

public function index2()
  {
    $users = $this->User->find('all', array(
      'conditions' => array(
        'User.id' => $this->User->ProblemsUser->find('list', array(
          'conditions' => array(
            'AND' => array('ProblemsUser.problem_id' => 1, 'ProblemsUser.problem_id' => 2)
          ),
          'fields' => array('user_id')
        ))
      )
    ));
    
    pr($users);
    exit;
  }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question