Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
How to use self referential N-M relationship to make 2 users friends using RedBean PHP ORM?
I am working with PHP and RedBean PHP ORM. I have a table user
like so:
id | username
---|---------
1 | Alice
2 | Bob
I want Alice and Bob to become friends. So I want to create M-M junction table friend
that will look something like this:
id | friend_1_id | friend_2_id
---|-------------|------------
1 | 1 | 2
friend_1_id
and friend_2_id
should be a foreign key reference to user
.
In RedBean PHP ORM documentation at the bottom of Many-to-Many page there is a section titled "Self referential N-M". Here is the content of that section:
You can have a shared list containing beans of the same type as the owner of the list:
$friends = $friend->sharedFriend;
In this case RedBeanPHP will operate in a special self-referential many-to-many relationship mode. It will not only retrieve all friends of $friend, but also all other friends that are associated with $friend.
I don't find this section to be informative enough. I suspect that this is exactly what I need, however, I cannot figure out how to make it work. Here is what I tried:
$u1 = R::findOne("user", "id = 1");
$u2 = R::findOne("user", "id = 2");
$u1->sharedFriend = $u2;
R::store($u1);
Instead of creating friend
table and linking 2 users it added sharedFriend_id
column to user
table and now it looks like this:
id | username | sharedFriend_id
---|----------|----------------
1 | Alice | 2
2 | Bob | NULL
Questions:
- How can I implement self-referential N-M with RedBean PHP?
- If "self-referential N-M" is not the correct approach for the problem I want to solve then what would be the most "RedBean PHP"-ish way of making two users friends?
Note: In the past I managed stuff like this manually by writing all the necessary logic myself. I would rather avoid doing that and learn how to do it properly using this framework if it is possible.
0 comment threads