-
Notifications
You must be signed in to change notification settings - Fork 65
/
BelongsToRelationship.class.php
93 lines (73 loc) · 2.39 KB
/
BelongsToRelationship.class.php
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
<?php
class BelongsToRelationship extends Relationship {
function getType() {
return 'BelongsTo';
}
function init($modelClassName, $relationshipName) {
$this->localClass = $modelClassName;
$this->name = $relationshipName;
$this->onDelete = Relationship::NULLIFY;
$this->foreignKey = Inflector::toUnderscores($relationshipName) . '_id';
$this->foreignClass = Inflector::toProperCaps($relationshipName);
}
function attachMethodsToModelDescriptor(ModelDescriptor &$descriptor) {
$alias = $this->name;
$attachedMethod = new RecessClassAttachedMethod($this, 'selectModel', $alias);
$descriptor->addAttachedMethod($alias, $attachedMethod);
$alias = 'set' . ucfirst($this->name);
$attachedMethod = new RecessClassAttachedMethod($this,'set', $alias);
$descriptor->addAttachedMethod($alias, $attachedMethod);
$alias = 'unset' . ucfirst($this->name);
$attachedMethod = new RecessClassAttachedMethod($this,'remove', $alias);
$descriptor->addAttachedMethod($alias, $attachedMethod);
}
function set(Model $model, Model $relatedModel) {
if(!$relatedModel->primaryKeyIsSet()) {
$relatedModel->insert();
}
$foreignKey = $this->foreignKey;
$relatedPrimaryKey = Model::primaryKeyName($relatedModel);
$model->$foreignKey = $relatedModel->$relatedPrimaryKey;
$model->save();
return $model;
}
function remove(Model $model) {
$foreignKey = $this->foreignKey;
$model->$foreignKey = '';
$model->save();
return $model;
}
protected function augmentSelect(PdoDataSet $select) {
$select = $select
->from(Model::tableFor($this->foreignClass))
->innerJoin(Model::tableFor($this->localClass),
Model::primaryKeyFor($this->foreignClass),
Model::tableFor($this->localClass) . '.' . $this->foreignKey);
$select->rowClass = $this->foreignClass;
return $select;
}
function selectModel(Model $model) {
$select = $this->augmentSelect($model->select());
if(isset($select[0])) {
return $select[0];
} else {
return null;
}
}
function selectModelSet(ModelSet $modelSet) {
return $this->augmentSelect($modelSet);
}
function onDeleteCascade(Model $model) {
$this->selectModel($model)->delete();
}
function onDeleteDelete(Model $model) {
$relatedModel = $this->selectModel($model);
if($relatedModel != null) {
$relatedModel->delete(false);
}
}
function onDeleteNullify(Model $model) {
// no-op
}
}
?>