mysql 外键引用_MySQL:一个表中的两个外键引用另一个表

bd96500e110b49cbb3cd949968f18be7.png

I've come across something that seemed simple before but has me scratching my head again. I have a table for users:

user_id (PK) | username| email | something

... and a table for "views" for when one user has viewed another user:

view_id (PK) | viewer_id | viewed_id | view_date

The "viewer_id" and "viewed_id" are both user_ids, allowing me to search separately for instances when a user was the viewer or the one being viewed.

I initially thought that both of these columns would be foreign keys, but having created the tables in my schema.yml file (I'm using Doctrine 1.2) and specified two separate foreign relationships (one for each column), it seems Doctrine only takes into account the first listed foreign relationship between these two tables (user_id > viewer_id).

It's got me confused now whether this is correct MySQL behaviour, a problem in Doctrine, or a problem in the way I'm approaching this, or nothing to worry about! Can there be two separate foreign keys from one table mapped to the same column in another table? Is it even logical, given that a JOIN would still give me access to "views" through a user_id? Have I got it wrong?

Thanks for your time.

EDIT - The schema file:

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

解决方案

And here we go:

You specified the same aliases for the relations.

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

Or you set up the whole many-to-many relation differently:

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

and View should look like

View:

columns:

viewed_id:

type: integer

primary: true

viewer_id:

type: integer

primary: true

See the Doctrine documentation on many-to-many relationships.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值