2009-08-09 44 views
2

我有2個表:記錄排序爲:n(一對多)關係

+-----------+ +------------------------------------+--------------+ 
+ persons | | photos           | 
+-----------| +---------------------------------------------------+ 
+ id | name + | id | person_id | path    | title  | 
+-----------+ +---------------------------------------------------+ 
+ 1 | Tom + | 1 |   2 | ~fred/me.png  | Yo, it's Me! | 
+ 2 | Fred + | 2 |   2 | ~fred/my_wife.png | I'm Susan | 
+ 3 | Jack + | 3 |   1 | ~tom/my_dog.jpg | a woof  | 
+-----------+ +---------------------------------------------------+ 

具有在這種關係:

人的hasMany照片< - >照片屬於人

我想列出所有人與他們的照片(即使有人沒有一個,如傑克)和照片的順序命名。

我應該爲此編寫什麼SQL查詢(MySQL)?我可以在一對多關係中使用連接嗎?

PS:只是作爲一個信息,我希望能夠建立這樣一個陣列中的記錄:

$persons = Array(
    [0] => Array(
     [id] => 1, 
     [name] => 'Tom', 
     [Photo] => Array(
      [0] => Array(
       [id] => 3, 
       [person_id] => 1, 
       [path] => '~tom/my_dog.jpg', 
       [title] => 'a woof'    // 1st 
      ) 
     ) 
    ), 
    [1] => Array(
     [id] => 2, 
     [name] => 'Fred', 
     [Photo] => Array(
      [0] => Array(
       [id] => 2, 
       [person_id] => 2, 
       [path] => '~fred/my_wife.png', 
       [title] => "I'm Susan"   // 2nd 
      ), 
      [0] => Array(
       [id] => 1, 
       [person_id] => 2, 
       [path] => '~fred/me.png', 
       [title] => "Yo, it's Me!"  // 3rd 
      ) 
     ) 
    ), 
    [2] => Array(
     [id] => 3, 
     [name] => 'Jack', 
     [Photo] => Array() 
    ) 
) 

非常感謝!

回答

4
​​
+0

+1擊敗了我,抹去了我自己的帖子:) – 2009-08-09 19:50:29

相關問題