doudeng8691 2012-11-08 17:17
浏览 33
已采纳

ORM:友谊/佛教徒的关系

I'm trying to use ORM for the first time, I've defined the models like this:

User model:

class User extends Eloquent
{
    public function friends()
    {
       return $this->has_many_and_belongs_to('User', 'friends', 'user1_id', 'user2_id');
    }    
}

Friend model:

class Friend extends Eloquent
{
    public function friend()
    {
        return $this->belongs_to('User', 'user_id');
    }    
}

Friends mysql table:

id (pkey) # user1_id (references users.user_id) # user2_id (references users.user_id)

Right now by using $user->friends I get a unilateral list because the friends database parameters could be in any order (user1 is friend of user2 OR user2 is friend of user1). This would be ok if I was trying to use following/followers approach, but I want it to be reciprocal.

What is the best way to do this kinda of stuff? Inserting duplicated user1/user2 and user2/user1 on the database doesn't sound like a good approach and I wouldn't even know how to translate this to the ORM. Also, it seems the Friend model is not being used/getting called at all.

I'm also going to have a similar problem on the invite friend system.

  • 写回答

1条回答 默认 最新

  • doufu3718 2012-11-08 17:25
    关注

    You are looking for a Many to Many relationship, between Users! Check out how you can do this in Doctrine: Doctrine - Many to Many Self Referencing. Doctrine example might help you to get started.

    The idea is that you have one Entity, Users, and they can be friends with each other.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi