I'm trying to create a social-network like feature in an app I'm building, and Want to associate a Friend with another Friend.
Assume I have this:
Friend:
connection: doctrine
tableName: friend
colum开发者_JAVA百科ns:
id:
type: integer(8)
primary: true
autoincrement: true
name:
type: string(75)
notnull: true
How do I create a many to many relationship to associate Friend with itself?
Thanks ahead of time for your help..
Use self-referencing equal nest relations.
From the docs:
Equal Nest Relations
Equal nest relations are perfectly suitable for expressing relations where a class references to itself and the columns within the reference class are equal.
This means that when fetching related records it doesn't matter which column in the reference class has the primary key value of the main class.
The previous clause maybe hard to understand so lets take an example. We define a class called User which can have many friends. Notice here how we use the 'equal' option.
// models/User.php
class User extends BaseUser
{
public function setUp()
{
parent::setUp();
// ...
$this->hasMany('User as Friends', array(
'local' => 'user1',
'foreign' => 'user2',
'refClass' => 'FriendReference',
'equal' => true,
)
);
}
}
// models/FriendReference.php
class FriendReference extends Doctrine_Record
{
public function setTableDefinition()
{
$this->hasColumn('user1', 'integer', null, array(
'primary' => true
)
);
$this->hasColumn('user2', 'integer', null, array(
'primary' => true
)
);
}
}
Here is the same example in YAML format. You can read more about YAML in the YAML Schema > Files chapter:
---
# schema.yml
# ...
User:
# ...
relations:
# ...
Friends:
class: User
local: user1
foreign: user2
refClass: FriendReference
equal: true
FriendReference:
columns:
user1:
type: integer
primary: true
user2:
type: integer
primary: true
精彩评论