Mapping object relations - Join table associations - Many-to-Many.php 1.23 KB
Newer Older
doctrine's avatar
doctrine committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
<?php
class User extends Doctrine_Record { 
    public function setUp() {
        $this->hasMany("Group","Groupuser.group_id");
    }
    public function setTableDefinition() {
        $this->hasColumn("name","string",30);
    }
}

class Group extends Doctrine_Record {
    public function setUp() {
        $this->hasMany("User","Groupuser.user_id");
    }
    public function setTableDefinition() {
        $this->hasColumn("name","string",30);
    }
}

class Groupuser extends Doctrine_Record { 
    public function setTableDefinition() {
        $this->hasColumn("user_id","integer");
        $this->hasColumn("group_id","integer");
    }
}


$user = new User();

// add two groups
$user->Group[0]->name = "First Group";

$user->Group[1]->name = "Second Group";

// save changes into database
$user->save();

zYne's avatar
zYne committed
38 39 40 41
// deleting the associations between user and groups it belongs to

$user->Groupuser->delete();

42
$groups = new Doctrine_Collection($conn->getTable("Group"));
doctrine's avatar
doctrine committed
43 44 45 46 47 48 49 50 51 52

$groups[0]->name = "Third Group";

$groups[1]->name = "Fourth Group";

$user->Group[2] = $groups[0];
// $user will now have 3 groups

$user->Group = $groups;
// $user will now have two groups 'Third Group' and 'Fourth Group'
zYne's avatar
zYne committed
53

doctrine's avatar
doctrine committed
54
?>