How to check if two records have a self-referencing relation?
Posted
by Machine
on Stack Overflow
See other posts from Stack Overflow
or by Machine
Published on 2010-03-08T10:56:51Z
Indexed on
2010/03/08
11:21 UTC
Read the original article
Hit count: 276
Consider the following schema with users and their collegues (friends):
Users
User:
columns:
user_id:
name: user_id as userId
type: integer(8)
unsigned: 1
primary: true
autoincrement: true
first_name:
name: first_name as firstName
type: string(45)
notnull: true
last_name:
name: last_name as lastName
type: string(45)
notnull: true
email:
type: string(45)
notnull: true
unique: true
relations:
Collegues:
class: User
local: invitor
foreign: invitee
refClass: CollegueStatus
equal: true
onDelete: CASCADE
onUpdate: CASCADE
Join table:
CollegueStatus:
columns:
invitor:
type: integer(8)
unsigned: 1
primary: true
invitee:
type: integer(8)
unsigned: 1
primary: true
status:
type: enum(8)
values: [pending, accepted, denied]
default: pending
notnull: true
Now, let's say I two records, one for the user making a HTTP request (the logged in user), and one record for a user he wants to send a message to. I want to check if these users are collegues.
Questions:
- Does Doctrine have any pre-build functionality to check if two records with with self-relations are related?
- If not, how would you write a method to check this?
- Where would you put said method? (In the User-class, UserTable-class etc)
I could probably do something like this:
public function (User $user1, User $user2) {
// Ensure we load collegues if $user1 was fetched with DQL that
// doesn't load this relation
$collegues = $user1->get('Collegues');
$areCollegues = false;
foreach($collegues as $collegue) {
if($collegue['userId'] === $user2['userId']) {
$areCollegues = true;
break;
}
}
return $areCollegues;
}
But this looks a neither efficient nor pretty. I just feel that it should be solved already for self-referencing relations to be nice to use.
© Stack Overflow or respective owner