2010-05-23 98 views
0

所以我有一個表格模式,有可以成爲朋友的用戶。Symfony FK約束問題

User: 
    actAs: { Timestampable: ~ } 
    columns: 
    name: { type: string(255), notnull: true } 
    email: { type: string(255), notnull: true, unique: true } 
    nickname: { type: string(255), unique: true } 
    password: { type: string(300), notnull: true } 
    image: { type: string(255) } 

FriendsWith: 
    actAs: { Timestampable: ~ } 
    columns: 
    friend1_id: { type: integer, primary: true } 
    friend2_id: { type: integer, primary: true } 
    relations: 
    User: { onDelete: CASCADE, local: friend1_id, foreign: id } 
    User: { onDelete: CASCADE, local: friend2_id, foreign: id } 

它正確地構建數據庫,但是當我嘗試插入測試數據,如:

User: 
    user1: 
    name: Danny Gurt 
    email: [email protected] 
    nickname: danny 
    password: test1 
    user2: 
    name: Adrian Soian 
    email: [email protected] 
    nickname: adrian 
    password: test1 

FriendsWith: 
    friendship1: 
    friend1_id: user1 
    friend2_id: user2 

我得到這個完整性約束問題:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`krowdd`.`friends_with`, CONSTRAINT `friends_with_ibfk_1` FOREIGN KEY (`friend1_id`) REFERENCES `user` (`id`) ON DELETE CASCADE) 

任何想法?

此外:

我注意到了生成的SQL代碼只顯示了friends_with表的一個約束:

ALTER TABLE friends_with ADD CONSTRAINT friends_with_friend2_id_user_id FOREIGN KEY (friend2_id) REFERENCES user(id) ON DELETE CASCADE; 

也許這將幫助!

謝謝!

回答

2

名稱在FriendsWith表中的關係不同,從而可以主義正確地使用它們:

relations: 
    User1: { onDelete: CASCADE, local: friend1_id, foreign: id, foreignAlias: Friend1 } 
    User2: { onDelete: CASCADE, local: friend2_id, foreign: id, foreignAlias: Friend2 } 

的數字可能不是關係最好的名字,但你的想法。

更新 - CODE:

這應該爲你做的工作 - 請注意,我將在用戶表中的關係,而不是FriendsWith表:

relations: 
    Friend1: {class: FriendsWith, local: id, foreign: friend1_id, type: many, foreignType: one, foreignAlias: User1, onDelete: CASCADE} 
    Friend2: {class: FriendsWith, local: id, foreign: friend2_id, type: many, foreignType: one, foreignAlias: User2, onDelete: CASCADE} 
+0

仍然未解決問題。順便說一句,這些表都需要被稱爲用戶,因爲它們引用了實際的表名。我仍然得到和以前一樣的sql錯誤。我確實注意到一些奇怪的事情。當我檢查生成的sql代碼時,只有一個約束爲friends_with表創建時,應該有兩個。我將在我原來的帖子中發佈代碼。 – Danny 2010-05-24 16:58:39

+0

還有一個叫做「class」的屬性,可以用來指定它所關聯的模型。將其設置爲指示正確的表格,然後重新命名關係。我有這個完全相同的問題,完全相同的情況,完全相同的問題。使用上述方法。讓我知道如果你不能使用它,我會發布你的代碼。 – Tom 2010-05-24 17:48:56

+0

嗨,湯姆。感謝您的幫助,但我仍然有點困惑。如果你可以發佈你的代碼,這將是超級有用的。再次感謝! – Danny 2010-05-24 18:33:45