duanchen6423
2014-09-10 13:55
浏览 54
已采纳

Laravel Eloquent - 表加入

I have one problem where I need help. I'm doing one project in learning purposes.

I have 2 tables, the first one is

USERS which contain id (PK, AI), username, email, password and so on...

Another table called

FRIENDS

contain user_a (FK to users.id), user_b (FK to users.id), status (0 - pending, 1 - confirmed)...

Lets say the current logged user have id 1.

I need to join this 2 tables and get complete friend list for currently logged user, so query trough table friends where user_a or user_b = currently logged user id, and get all data (from table users) for his friend... So lets say this:

user_a = 1, user_b = 2 userb_a = 3, user_b = 1

I need to get info for users 2, 3.

I hope so you understand what I need.

Btw I know how to do this without using Eloquent, but I need to use Eloquent.

Thanks a lot!

图片转代码服务由CSDN问答提供 功能建议

我有一个问题需要帮助。 我正在学习一个项目。

我有2个表,第一个是

USERS 包含id(PK,AI),用户名,电子邮件,密码等...

另一个名为

FRIENDS的表

包含user_a(FK到users.id),user_b(FK到users.id),状态(0 - 挂起,1 - 确认)... \ n

让我们说当前登录的用户有id 1。

我需要加入这2个表并获取当前登录用户的完整好友列表,所以查询槽表朋友在哪里 user_a或user_b =当前记录的用户ID,并获取他朋友的所有数据(来自表用户)...所以我们这样说:

user_a = 1,user_b = 2 userb_a = 3,user_b = 1

我需要获取用户2,3的信息。

我希望你能理解我需要的东西。

顺便说一下,我知道如何在不使用Eloquent的情况下做到这一点,但我需要使用Eloquent。

非常感谢!

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dongyuan7110 2014-09-10 15:15
    已采纳

    This is many to many relationship, so you need belongsToMany.

    // basic setup
    public function friends()
    {
        return $this->belongsToMany('User', 'friends', 'user_a', 'user_b')
          ->withPivot('confirmed');
    }
    

    However that's not all, since you want it to be bidirectional. This means you need to setup 2 relationships - here you can find exact solution for this:

    Friendship system with Laravel : Many to Many relationship

    评论
    解决 无用
    打赏 举报
查看更多回答(2条)

相关推荐 更多相似问题