Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/email/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 条令-多个模型在另一个模型中引用同一id字段_Php_Sql_Doctrine - Fatal编程技术网

Php 条令-多个模型在另一个模型中引用同一id字段

Php 条令-多个模型在另一个模型中引用同一id字段,php,sql,doctrine,Php,Sql,Doctrine,我有一个文件模型,以及多个(目前有3个)不同的其他模型(文章、作业、事件),它们都可以有文件,存储在文件模型中 问题是,当我通过CLI工具生成表时(./doctor build all reload),我会收到以下错误消息: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`my_database/ar

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

问题是,当我通过CLI工具生成表时(./doctor 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`))
文件定义为(在此定义的模型中未定义任何关系):

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

  relations:
    Files:
      type: many
      class: File
      local: id
      foreign: target_id
这是Doctrine生成的Php代码(BaseFile.Php):

我理解为什么会发生这种情况(不能为多个表设置约束),但不知道如果没有多个文件表或关联表,如何解决这个问题

有没有办法告诉条令,它不应该在文件模型中创建关系

有什么好主意吗?

如果需要,试试看,
关系:

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

您可以尝试以下方法:

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;
    }
}

也许有更好的方法,但在本例中,您有一个表,不需要任何关系,但您必须自己指定getter/setter。因此,这取决于您的目标是否会终止。

我可以问您为什么不使用关联表来解决它吗?这是一个非常灵活和高效的解决方案,因为它允许您将同一文件链接到不同的内容类型,而无需多次上传。对于您当前的模型,这是不可能的…我真的可以用一个关联表来解决这个问题吗?我如何让条令知道“类型”字段?我不知道如何让条令发生这种情况,但问题可能在于条令在创建另一个表之前添加一个依赖于另一个表的表。条令需要在文件和其他模型中创建关系,以便了解表之间的关系。尝试在文件模型中定义关系,并使用
owningSide:true
指令。我不明白你在这里想干什么。是否所有其他型号都有一个/多个相关文件或什么?
columns:
    id: { type: integer(4), notnull: true, primary: true, autoincrement: true }
    target_id:  { type: integer(4), notnull: true }
    model:       { type: string, notnull: true }
public function getArticles() {
    if (strcmp($this->getModel(), 'Articles')) {
        return Doctrine::getTable('Articles')->findOneById($this->getTargetId());
    } else {
        return false;
    }
}