基于HABTM关系的cakephp条件


cakephp conditions based on HABTM relation

User Model 具有以下关系:

public $hasMany = array(
'MyRecipe' => array(
'className' => 'Recipe',
)
);

我想选择所有拥有带有ID: 1,2食谱

的用户

我如何在选择中使用该条件:

$this->User->find('all', array(
 'conditions' => array(
 'Recipe.Id' => [1,2]
)
));

但是在这个例子中,我也会得到没有食谱的用户,如何防止这种情况?

请在用户模型中给出这种关系

class User extends AppModel
{
    var $name = 'User';
    var $belongsTo = array("Recipe");
}

在用户控制器中,您的查询为

$list = $this->User->find('all',array("conditions"=>array("recipe_id IN"=>  [1,2] )));

它提供了您想要的输出。