首页 文章

Laravel ORM友谊关系没有重复

提问于
浏览
8

用雄辩的方式塑造友谊关系的最佳方式是什么?我的表架构在下面,我想定义一个关系,我可以检索所有的朋友,如下所示 .

<?php

class User extends Eloquent {

public function friends() {
    return $this->belongsToMany('User', 'friendships', 'user_id', 'friend_id')->orWhere($this->id,'=', 'friend_id');
  }
}

+----+---------+-----------+----------+---------------------+---------------------+
| id | user_id | friend_id | state    | created_at          | updated_at          |
+----+---------+-----------+----------+---------------------+---------------------+
|  1 |       3 |         1 | accepted | 0000-00-00 00:00:00 | 0000-00-00 00:00:00 |
|  2 |       2 |         3 | accepted | 0000-00-00 00:00:00 | 0000-00-00 00:00:00 |
+----+---------+-----------+----------+---------------------+---------------------+

当我寻找用户ID为3的朋友时,上面的关系接近工作我得到了用户1和3,但显然我想要1和2 .

Friendship Table

user_id:请求友谊的用户ID
friend_id:目标朋友的用户ID
州:友谊是否正在等待,接受或阻止 .
created_at和updated_at

我知道有Laravel Many to many self referencing table only works one way的解决方案,我可以从关系的两边检索朋友,但我必须是两行,例如,如果用户1和3是朋友,那么在一行user_id = 3和friend_id = 1,在下一行反之亦然 . (或者,如果我没有两行,我必须进行两次查询) .

3 回答

  • 4

    您不应该尝试将两行应该转换为一行,但如果您要尝试这样做,那么您绝对不需要两次访问数据库:

    select * from users where (user_id = :user_id and friend_id = :friend_id) or  (friend_id = :friend_id and user_id = :user_id)
    

    在Laravel中将是:

    Users::whereRaw('(user_id = ? and friend_id = ?) or (friend_id = ? and user_id = ?)', [            
        $user_id,
        $friend_id,
        $friend_id,
        $user_id
    ]);
    

    你也可以做分组来分组,但这有点复杂 .

  • 6

    您可以执行两次查找,and use a union query,因此只能访问数据库一次 . 将所有这些放在自定义函数中:

    class User extends Eloquent {
    
      public function friends()
      {
         $first = $this->belongsToMany('User', 'friendships', 'user_id', 'friend_id');  
         return $this->belongsToMany('User', 'friendships', 'friend_id', 'user_id')->union($first);  
      }
    }
    
  • -3

    我有一个建议,你使用条件来加载你想要的vlaues

    在这个例子中

    • 假设您使用查询来加载带有条件的user_id和fiend_id,

    “select * from frienddship WHERE user_ID ='$ id'或friend_ID ='$ id'”

    $ id:是您要向朋友展示的用户ID .

    在PHP中的WHILE循环中,您将用于加载结果,您可以通过创建条件来过滤resulets

    while ... {
    
    if (friendship['user_id'] == $id) {
    
    $f_id = friendship['friend_id'] ;  }
    
    // other instructionS...
    
    else  {
    
    $f_id = friendship['user_id'] ;  } 
    
    // other instructionS...
    
    }
    

    在这种情况下,您将从表列中加载数据,然后每次使用用户ID过滤列,并且只让他朋友的id,过滤器用于不向用户说您自己是朋友 .

    sorry i used mysql to explain the example

相关问题