与 PHP 学说的关联
我正在尝试使用 Doctrine (PHP) 将两个对象关联起来。
我有两个对象:用户和对话
一个用户有很多对话,一个对话最多属于两个用户(对话的发起者和一个接收者)。
因此,在我的 Doctrine 类中,我在 Conversation 类中有这个:
$this->hasOne('User as Initiator', array('local' => 'initiator_id', 'foreign' => 'id'));
$this->hasOne('User as Responder', array('local' => 'responder_id', 'foreign' => 'id'));
在 User 类中:
$this->hasMany('Conversation as Conversations', array('local'=> 'id', 'foreign'=> ????));
对于这个外键,我想添加一些表示“initiator_id OR responder_id”的内容。
我想我需要一个连接表来完成我想做的事情?在这种情况下你会怎么做?
谢谢你的回答,
马丁
I'm trying to do an association of two objects with Doctrine (PHP).
I have two objects : User and Conversation
One user has many conversations and a conversation belongs to two users maximum (on initiator of the conversation, and one receiver).
So, in my Doctrine class I have this in the Conversation class :
$this->hasOne('User as Initiator', array('local' => 'initiator_id', 'foreign' => 'id'));
$this->hasOne('User as Responder', array('local' => 'responder_id', 'foreign' => 'id'));
And in the User class :
$this->hasMany('Conversation as Conversations', array('local'=> 'id', 'foreign'=> ????));
For this foreign key I'd like to put something that means "initiator_id OR responder_id".
I guess I need a junction table to accomplish what I want to do ? What would you do in this case ?
Thank you for your answers,
Martin
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我的猜测是这样的:
my guess would be this:
我认为最好将
Conversation
和User
表之间的关系重新建模为多个。因为即使一次对话只有 2 个用户,他们仍然被视为多个用户。在前面的解决方案中,让两个与同一个表(对话)具有多个关系是一种开销。因为每次查询对话时,您最终都会做两倍的工作。
我的建议是将转换和用户之间的关系更改为 hasMany 并使用包含
conversion_id
、user_id
的关联类ConversationParticipants
来引用它们以及一个名为type
的附加关联属性,用于指示用户的类型(发起者/响应者)。所以你最终会得到类似于这个的东西(代码没有经过测试!)
这就是我在任何 ORM 上实现它的方式,但我不确定你是否可以在 Doctrine 中使用关联属性,或者这种成型方式是否有效,因为我不是 Doctrine 方面的专家
我希望这对您有帮助,,,
I think it would be better to re model the relation between the
Conversation
andUser
tables to manytomany. because even though a conversation have only 2 users, they are still considered more than one.In the previous solution, Having Two has-many relations with the same table (Conversation) is an over head. because you will end up doing twice the work every time you query a a conversation.
My suggestion is to change the relation between the conversion and the user to hasMany and reference them using an association class
ConversationParticipants
that contains theconversion_id
,user_id
and an additional association attribute calledtype
to indicate the type of the user (Initiator/Responder).So you will end up with something similar to this ( the code is not tested !)
This is how i would've implemented it on any ORM, I'm not sure though if you can use association attributes in Doctrine or if this way of molding is going to work as I'm not an expert in Doctrine
I Hope this was helpful ,,,