0

我有 2 个模型 Scale 和 Step,其中模型 Scale 有很多 Step。数据库表是:

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

你能帮我语法吗?

4

2 回答 2

1

我建议你改变你的数据库结构。而不是在 Scale 中将 Step 绑定到 s1、s2、s3...等,这有一些缺点,其中一个是它限制您每个 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";    
}
于 2013-02-09T15:14:59.597 回答
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.'')
        ));
于 2013-02-09T15:21:44.867 回答