Find Condition by And doen't work + cakephp

情到浓时终转凉″ 提交于 2019-12-04 06:51:02

问题


This function is working on OR condition. I need this to work with AND condition. Any help:

$ands = array();
foreach ($array_training_id as $id) {
        $ands[] = array('TrainingsUser.training_id' => $id);
}
$conditions = array('AND' => $ands);
$users = $this->TrainingsUser->find('all', array('conditions' => $conditions));

I'd like to write a query AND condition like this:

SELECT user_id FROM trainings_users WHERE training_id = 172 AND training_id = 174

This query is working when is getting the first id.
Table explanation: I have 3 table Training - User - Training_users... Training_users table have the traing_id and user_id What I want I need is some thing like this : SELECT user_id FROM Training_users WHERE training_id = 172 AND training_id = 174... which it doesn't work even in SqlMyadmin


what i need when I give training_id 172 AND training_id 174 it have to return user 150 only


回答1:


Why is your $array_project_id a string in the first place (besides the naming conflict^^)? It should be an array of ids and cake will automatically be able to work with it out of the box.

Well, anyway:

$ids = explode(',', $array_project_id);
// now its a clean array

$users = $this->Training->find('all', array('conditions' => 
    array('Training.Project_id' => $ids)
));

After your comments I still don't see the value in using AND here. But what the heck, here you go:

$ands = array();
foreach ($ids as $id) {
    $ands[] = array('Training.Project_id' => $id);
}
$conditions = array('AND' => $ands);
$users = $this->Training->find('all', array('conditions' => $conditions));

Voila. It will still never work, though.

It seems you are using some HABTM relation (you should have provided this vital piece of information in the beginning!). Then you need to query the intermediate model/relation in order to have two belongsTo-relations (= left joins) here.

What you REALLY need (again: why did you just post the relevant relation and the information about Training_users now?) is to query the intermediate table "Training_users" with one contain in the belongsTo direction (left joins to users). And the most important fact: using OR instead of AND. This will get the results you want.




回答2:


The easiest approach would be, to create a habtm-relation.

Then you can do:

$users = $this->User->Training->find('all', array('conditions' => array('User.id =' => $ids)));

This finds all where User.id = $id

With your AND-condition, it would be:

 $users = $this->User->Training->find('all', array('conditions' => 
'AND' => array('User.id =' => $ids['n'], 'User.id =' => $ids['n'])
));


来源:https://stackoverflow.com/questions/14879391/find-condition-by-and-doent-work-cakephp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!