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

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));
    

Open Source Object Relational Mapping in PHP

Download Porte 0.2.1