我有两个相关的模型。现在我需要从Field-Model中检索UserField上的连接条件匹配的数据:
我有UserField的ID并希望得到它的相关字段(-data): 相应的sql看起来像这样:
SELECT Field.*
FROM fields AS Field
JOIN user_fields AS UserField
ON UserField.field_id = Field.id
WHERE UserField.id = 3;
我想用蛋糕模型逻辑来写这个。
class Field extends AppModel {
public $hasMany = array(
'UserField' => array(
'className' => 'UserField',
'foreignKey' => 'field_id'
)
);
}
class UserField extends AppModel {
public $belongsTo = array(
'Field' => array(
'className' => 'Field'
)
);
}
$this->Field->hasMany['UserField']['conditions'] = array('UserField.id' => 3);
$this->Field->find('all');
查询的结果都是字段,而UserField仅在条件匹配时设置。我需要将结果限制为仅匹配的情况:
array(
(int) 0 => array(
'Field' => array(
'id' => (int) 1
),
'UserField' => array()
),
(int) 1 => array(
'Field' => array(
'id' => (int) 2
),
'UserField' => array()
),
(int) 2 => array(
'Field' => array(
'id' => (int) 3
),
'UserField' => array(
'id' => (int) 3
)
)
)
array(
(int) 2 => array(
'Field' => array(
'id' => (int) 3
),
'UserField' => array(
'id' => (int) 3
)
)
)
UserField是可选的,我只想检索Field数据。
答案 0 :(得分:0)
你想做这样的事我相信:
$rows = $this->Field->find('all', array(
'conditions' => array(
'UserField.id' => 3
)
);