Defining and using many-to-many associations
Two types of records are related with a many-to-many associations if they both define matching properties with "has_many" keys.
Porte provide two strategies to internally store "many-to_many" associations:
Plural and singular conversion of the properties are automatically handled.
Methods available with a "has_many" association
- Method get{Records}
- Method add{Records}
Add one or more associated record to the current record. It either accept an array of new or saved record, an array of integer or string primary keys or a string with a list of primary keys separated by commas. Calling the save method on the current record will also save the provided associated records.
- param PorteRecord || int || string: The associated record or its primary key value
- return PorteRecord: The current record
- Method add{Record}
Add an associated record to the current record. It either accept a new record, a saved record or the primary key value of a saved record. Calling the save method on the current record will also save the provided associated record.
- param PorteRecord || int || string: The associated record or its primary key value
- return PorteRecord: The current record
- Method delete{Records}
- Method delete{Record}
Quick exemple
Let's take an exemple: a group can have many users, and a user can be member of different groups. There are 2 strategies to manage this kind of relationship in the database: using a join table or with a list of primary keys. Both strategies are implemented, it just depend on the way you declare the has_many property in the meta_fieds configuration array.
The methods available when an has_many relationship is defined
class Groups extends PorteRecord{
$meta_fields = array(
'users' => array(
'has_many' => true
)
)
}
class User extends PorteRecord{
$meta_fields = array(
)
}
$group = new Group();
$group->load(12);
$user1 = new User();
$user2 = new User();
$user3 = new User();
// get method:
$group->getUsers();
// add method
$group->addUser($user1);
$group->addUser($user2);
$group->addUser($user3);
$group->save();
// delete methods
$group->deleteUser($user1);
$group->deleteUsers(array($user2,$user3));
// set method
$group->setUser(array($user1));