2012-10-31 166 views
0

在CakePHP如果我運行下面的find命令如何根據CakePHP中的子結果限制查詢結果?

$this->Instructor->find('all'); 

返回以下:

Array 
(
    [0] => Array 
     (
      [Instructor] => Array 
       (
        [id] => 1 
        [user_id] => 3 
        [bio] => A billionaire playboy, industrialist and ingenious engineer, Tony Stark suffers a severe chest injury during a kidnapping in which his captors attempt to force him to build a weapon of mass destruction. He instead creates a powered suit of armor to save his life and escape captivity. He later uses the suit to protect the world as Iron Man. 
       ) 

      [User] => Array 
       (
        [id] => 3 
        [first_name] => Tony 
        [last_name] => Stark 
        [asurite_user] => tstark 
        [asurite_id] => 
        [password] => 
        [email] => [email protected] 
        [created] => 2012-10-30 09:57:36 
        [modified] => 2012-10-30 09:57:36 
       ) 

      [Course] => Array 
       (
        [0] => Array 
         (
          [id] => 1 
          [slug] => beatles 
          [sln] => AAA001 
          [course_number] => 
          [title] => The Beatles 
          [description] => This is a class about the Beatles. If this were a real description, more information would be listed here. 
          [state] => 
         ) 

        [1] => Array 
         (
          [id] => 2 
          [slug] => elvis 
          [sln] => AAA002 
          [course_number] => 
          [title] => Elvis: The King of Rock 
          [description] => All about the king of rock and roll, Elvis Presley. 
          [state] => 
         ) 

       ) 

     ) 

    [1] => Array 
     (
      ... 

有「導師」和「場」之間的許多一對多的關係。如何根據每個「講師」所屬的「課程」過濾結果?我嘗試沒有成功如下:

$instructors = $this->Instructor->find('all', array(
    'conditions' => array('Course.id' = 2) 
)); 

回答

1

如果您試圖根據您的子項目的條件來限制父項目,則可以通過子模型而不是主模型來執行主查詢,其餘爲contain()或使用MySQL聯接 - 可用在CakePHP中通過joins()

+0

爲查找選項添加「連接」正是我需要做的。它實際上與他們在底部給出的例子非常相似。 – PHLAK

0

您需要(重新)綁定與hasOne你的導師模型的關聯,並使用這些設置:

'CoursesInstructor' => array(
    'className' => 'CoursesInstructor', 
    'foreignKey' => false, 
    'conditions' => 'Instructor.id = CoursesInstructor.id'), 
'Course' => array(
    'className' => 'Course', 
    'foreignKey' => false, 
    'conditions' => 'CoursesInstructor.course_id = Course.id'); 

這將生成所需的正確的SQL加入和你的條件將起作用。

+0

這似乎違反直覺。 hasAndBelongsToMany關係完全符合我描述的目的(課程可以有多個教師並且教師可以有多個課程)。 – PHLAK