0

我创建了一个与 sfGuardUser 模型相关的 sfGuardUserProfile 模型。然后我定义了另一个与 sfGuardUserProfile 相关的模型。创建数据库时我没有收到任何错误,但是当我尝试将数据保存到操作文件中的 sfGuardUserProfile 时,我收到此错误:

SQLSTATE [23000]:完整性约束违规:1452 无法添加或更新子行:外键约束失败

在我的 schema.yml 中,我将关系定义为一对一。

我不确定为什么这会失败。Doctrine 是否根本不支持向已经有关系的模型添加新关系?

编辑 这是我的 schema.yml:

sfGuardUserProfile:
  tableName: sf_guard_user_profile
  columns:
    sf_guard_user_id: { type: integer(4) }
    email:            { type: string(255) }
  relations:
    User:
      class:        sfGuardUser
      type:         one
      foreignType:  one
      onDelete:     CASCADE
      local:        sf_guard_user_id
      foreign:      id
      foreignAlias: Profile

FacebookAccount:
  tableName: facebook_account
  columns:
    user_id: { type: integer(4) }
    page_id: { type: integer }
  relations:
    sfGuardUserProfile:
      type:         one
      foreignType:  one
      class:        sfGuardUserProfile
      local:        user_id
      foreign:      sf_guard_user_id
      onDelete:     CASCADE
      foreignAlias: FacebookAccount

执行此操作时遇到错误:

$profile = $this->getUser()->getProfile();
$profile->setEmail('someone@somewhere.com');
$profile->save();

生成的 SQL:

INSERT INTO sf_guard_user_profile (sf_guard_user_id, email) VALUES (?, ?) - (1, someone@somewhere.com)

确切的错误:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`site`.`sf_guard_user_profile`, CONSTRAINT `sf_guard_user_profile_sf_guard_user_id_facebook_account_user_id` FOREIGN KEY (`sf_guard_user_id`) REFERENCES `facebook_account` (`user_id`))
4

2 回答 2

2

我认为您的问题是您的 FacebookAccount 模型没有链接到您的 Profile 模型上的主键,而 Doctrine 不知道如何使用它。更改您的 FacebookAccount 以引用 Profile 主键:

  relations:
    sfGuardUserProfile:
      type:         one
      foreignType:  one
      class:        sfGuardUserProfile
      local:        user_id
      foreign:      id
      onDelete:     CASCADE
      foreignAlias: FacebookAccount

或与 sfGuardUser 的主键有关:

  relations:
    sfGuardUser:
      type:         one
      foreignType:  one
      class:        sfGuardUser
      local:        user_id
      foreign:      id
      onDelete:     CASCADE
      foreignAlias: FacebookAccount
于 2010-02-12T00:50:59.753 回答
1

您必须确保不会破坏数据库完整性:http: //msdn.microsoft.com/en-us/library/ms175464.aspx。您可以按正确的顺序插入行,例如:

$sfGuardUser = new sfGuardUser();
$sfGuardUser->id = 1;
$sfGuardUser->save();

$sfGuardUserProfile = new sfGuardUserProfile();
$sfGuardUserProfile->user_id = $sfGuardUser->id;
$sfGuardUserProfile->save();

或像这样:

$sfGuardUser = new sfGuardUser();
$sfGuardUser->id = 1;

$sfGuardUserProfile = new sfGuardUserProfile();
$sfGuardUserProfile->User = $sfGuardUser;
sfGuardUserProfile->save();
于 2010-02-11T20:10:16.773 回答