php - MySQL:一个表中的两个外键引用另一个表

标签 php mysql schema foreign-keys doctrine

我遇到过一些以前看似简单的事情,但又让我摸不着头脑。我有一个用户表:

user_id (PK) | username| email | something

...以及一个用户查看另一用户时的“ View ”表:

view_id (PK) | viewer_id | viewed_id | view_date

“viewer_id”和“viewed_id”都是 user_id,允许我单独搜索用户是查看者或被查看者的实例。

我最初认为这两列都是外键,但是在我的 schema.yml 文件中创建了表(我使用的是 Doctrine 1.2)并指定了两个单独的外关系(每列一个),看起来Doctrine 仅考虑这两个表之间第一个列出的外部关系 (user_id >viewer_id)。

现在让我感到困惑的是,这是否是正确的 MySQL 行为、Doctrine 中的问题、或者我处理此问题的方式中的问题,或者没什么可担心的!一个表中是否可以有两个单独的外键映射到另一表中的同一列?考虑到 JOIN 仍然可以让我通过 user_id 访问“ View ”,这是否符合逻辑?难道是我理解错了?

感谢您的宝贵时间。

编辑 - 架构文件:

User:
relations:
View: {class: View, local: user_id, foreign: viewer_id, type: many, foreignType: one, alias: View, foreignAlias: User}
View: {class: View, local: user_id, foreign: viewed_id, type: many, foreignType: one, alias: View, foreignAlias: User}

... only difference is viewer_id/viewed_id

最佳答案

我们开始吧: 您为关系指定了相同的别名。

User:
  relations:
    viewed_by: 
       class: View
       local: user_id
       foreign: viewed_id
       type: many
       foreignType: one
       foreignAlias: viewed

    viewed:
      class: View
      local: user_id
      foreign: viewer_id
      type: many
      foreignType: one
      foreignAlias: viewer

或者您以不同的方式设置整个多对多关系:

User:
   relations:
     viewed_by: 
       class: User 
       local: viewed_id
       foreign: viewer_id,
       refClass: View
     viewed:
       class: User
       local:viewer_id
       foreign: viewed_id
       refClass: View

View应该看起来像

View:
  columns:
    viewed_id:
      type: integer
      primary: true
    viewer_id:
      type: integer
      primary: true

请参阅 many-to-many relationships 上的 Dotrine 文档.

关于php - MySQL:一个表中的两个外键引用另一个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2171687/

相关文章:

php - 让 SQS 工作人员了解时区

php - 如何在 PHP 单元测试中模拟在构造函数中调用的方法?

mysql - 错误 - "Result consisted of more than one row",由于 GROUP BY

java - Hibernate criteria + Projection List中的计算

.net - Bug Tracker .NET - 如何仅从数据库确定版本?

sql - 将字段存储为单一文本类型 JSON 字符串与拆分到单独表的性能影响

XML XSD 架构 - 在架构中实现唯一属性值

php - mysql_pconnect 不工作

php - JavaScript 错误 : Object #<HTMLFormElement> has no method 'getElementById'

mysql - 选择查询并过滤至少一个匹配项