10.04.2018 Views

Doctrine_manual-1-2-en

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 7: Defining Models 77<br />

Here is the same example in YAML format. You can read more about YAML in the YAML<br />

Schema Files (page 195) chapter:<br />

---<br />

# schema.yml<br />

Listing<br />

7-66<br />

# ...<br />

UserGroup:<br />

columns:<br />

user_id:<br />

type: integer<br />

primary: true<br />

group_id:<br />

type: integer<br />

primary: true<br />

Notice how the relationship is bi-directional. Both User has many Group and Group has<br />

many User. This is required by <strong>Doctrine</strong> in order for many-to-many relationships to fully<br />

work.<br />

Now lets play around with the new models and create a user and assign it some groups. First<br />

create a new User instance:<br />

// test.php<br />

Listing<br />

7-67<br />

// ...<br />

$user = new User();<br />

Now add two new groups to the User:<br />

// test.php<br />

Listing<br />

7-68<br />

// ...<br />

$user->Groups[0]->name = 'First Group';<br />

$user->Groups[1]->name = 'Second Group';<br />

Now you can save the groups to the database:<br />

// test.php<br />

Listing<br />

7-69<br />

// ...<br />

$user->save();<br />

Now you can delete the associations betwe<strong>en</strong> user and groups it belongs to:<br />

// test.php<br />

Listing<br />

7-70<br />

// ...<br />

$user->UserGroup->delete();<br />

$groups = new <strong>Doctrine</strong>_Collection(<strong>Doctrine</strong>_Core::getTable('Group'));<br />

$groups[0]->name = 'Third Group';<br />

$groups[1]->name = 'Fourth Group';<br />

$user->Groups[2] = $groups[0];<br />

----------------- Brought to you by

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!