我有2个模型Scale和Step,其中model Scale有很多Step。 db表是:
scale : id | name | s1 | s2 | s3 | s4 | s5 | s6 | s7
step : id | val
我想在cakephp结构中编写以下查询...
select s.id, s1.val as v1, s2.val as v2, s3.val as v3, s4.val as v4, s5.val as v5, s6.val as v6, s7.val as v7
from scale s
join step s1 on s.s1 = s1.id
join step s2 on s.s2 = s2.id
join step s3 on s.s3 = s3.id
join step s4 on s.s4 = s4.id
join step s5 on s.s5 = s5.id
join step s6 on s.s6 = s6.id
join step s7 on s.s7 = s7.id
你能帮我解释一下语法吗?
答案 0 :(得分:1)
我建议您改变数据库结构。而不是将Step绑定到S1,s2,s3 ......等Scale,这有一些缺点,其中之一就是它限制你每个Scale只有7个步骤,而且实际上并不是一个好的关系数据库模型,我建议您创建第三个表,称为ScaleSteps,并有三列:
id | ScaleId | StepId
假设您有一个ID为7的Scale条目,并且该Scale具有与之关联的Step条目1,2和3,结果表将如下所示:
id | ScaleId | StepId
1 | 7 | 1
1 | 7 | 2
1 | 7 | 3
然后使用:hasOne,belongsTo ...等设置CakePHP模型关系,例如:
class Scale extends Model {
var $name = "Scale";
var $hasMany = "ScaleStep";
}
class ScaleStep extends Model {
var $name = "ScaleStep";
var $belongsTo = "Step";
}
答案 1 :(得分:0)
$this->find('all', array(
'fields' => array('s1.val', 's2.val'),
'joins' => array(array(
'table' => 'step',
'alias' => 's1',
'type' => 'inner',
'conditions' =>array('Scale.s1 = s1.id')
),array(
'table' => 'step',
'alias' => 's2',
'type' => 'inner',
'conditions' =>array('Scale.s2 = s2.id')
),
),
'conditions' => array('Scale.id = '.$id.'')
));