2013-02-09 151 views
0

我有2個模型縮放和步驟,其中模型縮放有很多步驟。 的數據庫表是:cakephp翻譯查詢cakephp模型查詢

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
$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.'') 
     )); 
1

我建議你也許改變你的數據庫結構。 Scale不是將Step綁定到Scale中的s1,s2,s3等等,它有一些缺點,其中之一就是它將每個Scale限制爲只有7個步驟,並且它不是一個很好的關係數據庫模型,我建議你創建一個第三個表,稱爲像ScaleSteps,並有三列:

id | ScaleId | StepId 

試想您有相關的7 ID的規模進入,而且規模有步驟項1,2,與之相關聯的3,得到的表是這樣的:

id | ScaleId | StepId 
1 | 7  | 1 
1 | 7  | 2 
1 | 7  | 3 

然後使用設置你的CakePHP模型關係:hasOne,屬於...等,例如:

class Scale extends Model { 
var $name = "Scale"; 
var $hasMany = "ScaleStep"; 
} 

class ScaleStep extends Model { 
var $name = "ScaleStep"; 
var $belongsTo = "Step";  
} 
+0

重要的是你的答案。我希望規模實際上被限制在只有七個步驟,這就是爲什麼我這樣設計它。我其實想通了...... – 2013-02-09 15:21:17

+0

沒問題。我認爲我得到了belongsTo,並且在我的答案中混雜了:)無論如何,很高興你解決了它。 – Crwydryn 2013-02-09 15:48:30