与 Laravel 的友谊系统:多对多关系
问题描述
我正在尝试使用 Laravel 创建一个友谊系统(我是从它开始的),但我被关系阻止了.事情是这样的:有一张表 Users 和一张表 Friends ,其中包含以下列:
I'm trying to create a Friendship system with Laravel (I'm starting with it) but I'm blocked with relationships. Here's the thing : there is one table Users and one table Friends which contains the following columns :
它看起来像多对多,所以这是我在用户类上设置的:
It looks like a Many to Many so here's what I set on User class :
但是当我尝试:
我有这个错误:
我想获取一个用户的好友列表,无论用户是发送邀请还是收到邀请.因此,用户可以根据 user_id 或friend_id 获取数据,然后根据该列检索其他用户的数据.
I would like to get a list of the Friends of a user, no matters if the user sent the invitation or received it. So the user can ba on user_id or on friend_id and then I retrieve the data of the other user depending of that column.
有什么想法吗?谢谢!
这是我使用的代码:
推荐答案
tldr;您需要 2 个反向关系才能使其工作,请检查下面的 SETUP 和 USAGE
<小时>首先是错误 - 这就是你的关系应该是什么样子:
tldr; you need 2 inverted relationships to make it work, check SETUP and USAGE below
First off the error - this is how your relation should look like:
然后它就会正常工作:
<小时>
设置
但是您希望关系以两种方式工作.Eloquent 不提供这种关系,因此您可以改为使用 2 个反向关系并合并结果:
SETUP
However you would like the relation to work in both ways. Eloquent doesn't provide a relation of that kind, so you can instead use 2 inverted relationships and merge the results:
用法
通过这样的设置,您可以做到:
USAGE
With such setup you can do this:
这篇关于与 Laravel 的友谊系统:多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!