数据库和查询存储和检索好友列表


Database and query to store and retrieve friend list

我正在开发一个网站模块来保存和检索好友列表。我使用Zend框架和DB处理我使用原则(ORM)。

有两个模型:

1) users存储所有用户
2) my_friends存储好友列表(即用户的M:M关系的引用表)

my_friends的结构如下

…id .......... user_id ............
friend_id批准……十……20 .................. 25 ................... 1 ..........
十……21 .................. 25 ................... 1 ..........
十……22 .................. 30 ................... 1 ..........
十……25 .................. 30 ................... 1 ..........


Doctrine 查询检索好友列表id

$friends = Doctrine_Query::create()->from('my_friends as mf')
                                 ->leftJoin('mf.users as friend')
                                 ->where("mf.user_id = 25")
                                 ->andWhere("mf.approved = 1");  

假设我正在查看用户号。- 25
使用此查询,我只获得用户号。- 30
其中为用户号。—25也是用户号的认可好友。- 20和21.
请指导我,应该是什么查询找到所有的朋友,是否有任何需要改变DB结构。

YAML
成员:
列:

id:
  primary: true
  type: integer
  notnull: true
  autoincrement: true
userName:
  unique: true
  type: string(255)
Address_id:
  type: integer(4)
MemberPhoto_id:
  type: integer
 relations:
address:
  class: Address
  local: Address_id
  foreign: id
memberPhotos:
  class: MemberThumbnail
  foreignAlias: member
  local: MemberPhoto_id
  foreign: id
refPeeps:
columns:
id:
  primary: true
  unique: true
  type: integer
  autoincrement: true
Member_id:
  type: integer
  notnull: true
Peep_id:
  type: integer
  notnull: true
relations:
Member:
  local: Member_id
  foreign: id
Member:
  local: Peep_id
  foreign: id

——你好安穆立特。

-我认为你需要用两个查询获取数据。在我看来,你必须遵循以下步骤

  1. 首先使用连接查询获取与friend_id对应的所有数据。
  2. 和第二次应用简单的查询user_id和获取数据。
  3. 然后获取第二个查询对应的数据。

我不是100%确定如何在Doctrine中表达这一点,因为我有一段时间没有使用它了,但您需要将my_friends加入到friend_id = user_id的位置。我当然可能误解了你的数据库布局。如果我误解了你,请用PHP模式或生成它的YAML文件更新你的问题。

我不知道学说,你的查询可能是。如果你能给出示例数据和示例结果,我可以更好地帮助你

SELECT *
FROM my_friend
LEFT JOIN users ON my_friend.friend_id = users.id
WHERE my_friend.user_id = 25

根据您的表,这是您应该收到的输出

因为您查询user_id,并且user_id=25只有一行

你有两种方法做你想做的事

1)当您添加好友时,您应该创建两行,一行是user_id=25和friend_id=30,另一行是user_id=30和friend_id=25

这有点难看,但在构建查询时具有优势

2)第二种方式不需要任何数据库保存更改,但需要更改查询您应该查询:

(user_id=25 or friend_id=25)。不只是user_id