2010-01-31 104 views
2

我遇到過一些看似簡單的東西,但又讓我再次撓撓頭。我有一個用戶表:MySQL:在一個表中引用另一個表的兩個外鍵

user_id (PK) | username| email | something 

...和「意見」,當一個用戶查看其他用戶的表:

view_id (PK) | viewer_id | viewed_id | view_date 

的「viewer_id」和「viewed_id」都是user_ids,允許我分別搜索用戶是查看者還是正在查看的實例。

我最初認爲這兩列都是外鍵,但是在我的schema.yml文件(我使用Doctrine 1.2)中創建了表並且指定了兩個單獨的外鍵關係(每列一個),它似乎學說只考慮了這兩個表之間的第一個列出的外部關係(user_id> viewer_id)。

現在是否讓我感到困惑,無論這是MySQL的行爲是否正確,教義中的問題,還是我接近這個問題的方式,或者沒有什麼可擔心的!一個表中可以有兩個單獨的外鍵映射到另一個表中的同一列嗎?鑑於JOIN仍然會讓我通過user_id訪問「視圖」,這是否合乎邏輯?我弄錯了嗎?

謝謝你的時間。

編輯 - 架構文件:

User: 
relations: 
View: {class: View, local: user_id, foreign: viewer_id, type: many, foreignType: one, alias: View, foreignAlias: User} 
View: {class: View, local: user_id, foreign: viewed_id, type: many, foreignType: one, alias: View, foreignAlias: User} 

... only difference is viewer_id/viewed_id 
+0

你可以顯示你的模式文件的這一部分?也許你沒有正確設置它。 – 2010-01-31 12:51:11

+0

添加了模式文件。 – Tom 2010-01-31 12:55:05

回答

5

而這裏我們去: 您指定了關係的相同別名。

User: 
    relations: 
    viewed_by: 
     class: View 
     local: user_id 
     foreign: viewed_id 
     type: many 
     foreignType: one 
     foreignAlias: viewed 

    viewed: 
     class: View 
     local: user_id 
     foreign: viewer_id 
     type: many 
     foreignType: one 
     foreignAlias: viewer 

或者你設置了整個許多一對多的關係是不同的:

User: 
    relations: 
    viewed_by: 
     class: User 
     local: viewed_id 
     foreign: viewer_id, 
     refClass: View 
    viewed: 
     class: User 
     local:viewer_id 
     foreign: viewed_id 
     refClass: View 

View應該像

View: 
    columns: 
    viewed_id: 
     type: integer 
     primary: true 
    viewer_id: 
     type: integer 
     primary: true 

參見many-to-many relationships教義文檔。

+0

謝謝Felix,讓我試試看。 – Tom 2010-01-31 13:17:47

+0

頂部的Alias修復程序爲我解決了它。需要花更多時間閱讀文檔,以便正確理解它。謝謝你的幫助! – Tom 2010-01-31 13:29:47

+0

謝謝!它在我的項目中幫助了我很多。 – GiantRobot 2012-01-07 19:17:02

1

MySQL允許在同一個表的多個外鍵,甚至到另一個表中的同一列,但我不知道爲什麼學說只創建其中之一:

mysql> CREATE TABLE test1 (id INT); 
Query OK, 0 rows affected (0.00 sec) 

mysql> CREATE TABLE test3 (ref1 INT, ref2 INT, FOREIGN KEY (ref1) REFERENCES test1(id), FOREIGN KEY (ref2) REFERENCES test1(id)); 
Query OK, 0 rows affected (0.01 sec) 
+0

謝謝,我認爲它縮小到我的模式語法。 – Tom 2010-01-31 13:17:30

相關問題