【问题标题】:Doctrine - Multiple models referencing same id field in another modelDoctrine - 多个模型在另一个模型中引用相同的 id 字段
【发布时间】:2011-02-21 09:51:00
【问题描述】:

我有一个文件模型,以及多个(目前 3 个)不同的其他模型(文章、工作、事件),它们都可以有文件,存储在文件模型中。

问题是当我通过 CLI 工具 (./doctrine build-all-reload) 生成表时,我收到以下错误消息:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot 
add or update a child row: a foreign key constraint fails 
(`my_database/articles`, CONSTRAINT `articles_id_files_target_id`
FOREIGN KEY (`id`) REFERENCES `files` (`target_id`))

文件被定义为(此模型中未定义任何关系):

columns:
  id:
    primary: true
    autoincrement: true
    type: integer(4)
  target_id: integer(4)
  filename: string(255)
[...]

所有 4 个模型都有这个关系定义:

  relations:
    Files:
      type: many
      class: File
      local: id
      foreign: target_id

这是 Doctrine 生成的 PHP 代码(BaseFile.php):

public function setUp()
{
    parent::setUp();
    $this->hasOne('Publication', array(
         'local' => 'target_id',
         'foreign' => 'id'));

    $this->hasOne('Event', array(
         'local' => 'target_id',
         'foreign' => 'id'));

    $this->hasOne('Article', array(
         'local' => 'target_id',
         'foreign' => 'id'));

    $this->hasOne('Job', array(
         'local' => 'target_id',
         'foreign' => 'id'));
}

我了解为什么会发生这种情况(无法为多个表设置约束),但不知道如何在没有多个文件表或关联表的情况下解决此问题。

有没有办法告诉 Doctrine 它不应该在 File 模型中创建关系?

有什么好主意吗?

【问题讨论】:

  • 请问您为什么不使用关联表来解决它?这是一个非常灵活和高效的解决方案,因为它允许您将同一个文件链接到不同的内容类型,而无需多次上传。使用您当前的模型这是不可能的......
  • 我真的可以用一个关联表来解决这个问题吗?我如何让教义知道“类型”字段?
  • 我不知道如何通过教义实现这一点,但问题可能在于教义添加一个依赖于另一个表的表之前另一个表已经已创建。
  • Doctrine 需要在文件和其他模型中创建关系,以便知道表之间的关系。尝试在 Files 模型中定义关系并使用 owningSide: true 指令。 doctrine-project.org/documentation/manual/1_2/en/…
  • 我对您在这里尝试做什么感到困惑。所有其他模型是否有一个/多个相关文件或什么?

标签: php sql doctrine


【解决方案1】:

如果需要,请尝试,
关系:

Files:
  type: many
  class: File
  local: target_id
  foreign: id
Files2:
  type: many
  class: File
  local: id
  foreign: id

【讨论】:

    【解决方案2】:

    你可以试试这样的:

    columns:
        id: { type: integer(4), notnull: true, primary: true, autoincrement: true }
        target_id:  { type: integer(4), notnull: true }
        model:       { type: string, notnull: true }
    

    文件模型需要知道链接条目的id和模型。所以,在 Files.class.php 中你也可以指定:

    public function getArticles() {
        if (strcmp($this->getModel(), 'Articles')) {
            return Doctrine::getTable('Articles')->findOneById($this->getTargetId());
        } else {
            return false;
        }
    }
    

    可能有更好的方法,但在这种情况下,您有 1 个表,您不再需要任何关系,但您必须自己指定 getter/setter。所以这是否会成功取决于你的目标。

    【讨论】:

      猜你喜欢
      • 2023-02-24
      • 2021-12-07
      • 1970-01-01
      • 2019-09-04
      • 1970-01-01
      • 1970-01-01
      • 2011-09-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多