-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathassociation.cr
56 lines (47 loc) · 1.24 KB
/
association.cr
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
require "../src/topaz"
require "sqlite3"
######################
# Association Sample #
######################
# You can define associations for each model
# For now, let me define 2 models
class SampleParent < Topaz::Model
columns # Empty columns
# This meant that SampleParent has multiple SampleChilds
# You can access it as children where parent_id of the children equals to the id
has_many(
children: {model: SampleChild, key: parent_id}
)
end
class SampleChild < Topaz::Model
# Define foreign key
columns(
parent_id: Int64
)
# This meant that SampleChild belongs to a SampleParent
# You can access SampleParent as parent where id of it equals to parent_id
belongs_to(
parent: {model: SampleParent, key: parent_id}
)
end
# Setup db
Topaz::Db.setup("sqlite3://./db/sample.db")
# Setup tables
SampleParent.drop_table
SampleParent.create_table
SampleChild.drop_table
SampleChild.create_table
# Let me create a parent
p = SampleParent.create
# Here we create 3 children belong to the parent
child1 = SampleChild.create(p.id.to_i64)
child2 = SampleChild.create(p.id.to_i64)
child3 = SampleChild.create(p.id.to_i64)
# Select all children
p.children.size
# => 3
p.children.first.id
# => 1
# Find a parent
child1.parent.id
# => 1