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!

  • 写回答

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条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?