所以我有一个表架构,其中包含可以成为 friend 的用户。
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: comy19@gmail.com
nickname: danny
password: test1
user2:
name: Adrian Soian
email: adriansoian@gmail.com
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;
也许这会有所帮助!
谢谢!
最佳答案
以不同的方式命名 FriendsWith 表中的关系,以便 Doctrine 可以正确使用它们:
relations:
User1: { onDelete: CASCADE, local: friend1_id, foreign: id, foreignAlias: Friend1 }
User2: { onDelete: CASCADE, local: friend2_id, foreign: id, foreignAlias: Friend2 }
这些数字可能不是关系的最佳名称,但你明白了。
更新 - 代码:
这应该可以为您完成工作 - 请注意,我在 User 表中添加关系,而不是 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}
关于php - Symfony FK 约束问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2893289/