Associations.ejs
2.87 KB
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<script type="text/javascript" charset="utf-8">
document.observe("dom:loaded", function() {
buildNavigation([], ["<br />", "<a href=\"/examples/Count\">Count</a>",
"<a href=\"/examples/DefaultValues\">Default values</a>",
"<a href=\"/examples/fetchAssociations\">fetchAssociations</a>",
"<a href=\"/examples/MethodPassing\">MethodPassing</a>",
"<a href=\"/examples/Performance\">Performance</a>",
"<a href=\"/examples/SequelizeWithOptions\">SequelizeWithOptions</a>",
"<a href=\"/examples/ChainQueries\">Using the chainQueries function</a>",
"<a href=\"/examples/UsingMultipleModelFiles\">UsingMultipleModelFiles</a>",
"<a href=\"/examples/Associations\">Working with associations</a>"], { seperator: ' ' })
})
</script>
<div>
<a name="sequelize"></a>
<h1>Working with associations</h1>
<p></p>
</div>
<div class="seperator"></div>
<div>
<a name="app.js"></a>
<h2>app.js</h2>
<p>
This example demonstrates the use of associations.
First of all, Person is getting associated via many-to-many with other Person objects (e.g. Person.hasMany('brothers')).
Afterwards a Person becomes associated with a 'father' and a mother using a one-to-one association created by hasOneAndBelongsTo.
The last association has the type many-to-one and is defined by the function hasManyAndBelongsTo.
The rest of the example is about setting and getting the associated data.
<pre>
var Sequelize = require(__dirname + "/../../lib/sequelize/Sequelize").Sequelize,
sequelize = new Sequelize("sequelize_test", "root", null, {disableLogging: true}),
Person = sequelize.define('person', {
name: Sequelize.STRING
}),
Pet = sequelize.define('pet', {
name: Sequelize.STRING
})
Person.hasMany('brothers')
Person.hasMany('sisters')
Person.hasOneAndBelongsTo('father', Person)
Person.hasOneAndBelongsTo('mother', Person)
Person.hasManyAndBelongsTo('pets', Pet, 'owner')
Sequelize.chainQueries([{drop: sequelize}, {sync: sequelize}], function() {
var person = new Person({ name: 'Luke' }),
mother = new Person({ name: 'Jane' }),
father = new Person({ name: 'John' }),
brother = new Person({ name: 'Brother' }),
sister = new Person({ name: 'Sister' }),
pet = new Pet({ name: 'Bob' })
Sequelize.chainQueries({save: [person, mother, father, brother, sister, pet]}, function() {
person.setMother(mother, function(mom) { Sequelize.Helper.log('my mom: ' + mom.name) })
person.setFather(father, function(dad) { Sequelize.Helper.log('my dad: ' + dad.name) })
person.setBrothers([brother], function(bros) { Sequelize.Helper.log("ma bro: " + bros[0].name)})
person.setSisters([sister], function(sis) { Sequelize.Helper.log("ma sis: " + sis[0].name)})
person.setPets([pet], function(pets) { Sequelize.Helper.log('my pet: ' + pets[0].name )})
})
})</pre>
</p>
</div>