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 |
<?php
/**
* Save any two HABTM related models at the same time... with existing record check
* i.e. Class HABTM Address, will save both at once. (if a given address does not exist
* yet will save address and relation, else will get existing Address.id and save relation)
*/
class HabtambleBehavior extends ModelBehavior {
//fields to skip during record check
//holds name of the related model
private $habtmModel;
}
$this->habtmModel = $this->settings['habtmModel'];
}
public function beforeSave(&$Model) {
$existingId = $this->getExistingId(&$Model);
$Model->data[$this->habtmModel][$this->habtmModel] = $existingId;
}
return TRUE;
}
private function getExistingId(&$Model) {
$conditions = $this->buildCondition($Model);
'recursive' => -1));
if(!$existingRecord) {
$Model->{$this->habtmModel}->create();
$Model->{$this->habtmModel}->save($Model->data[$this->habtmModel]);
$existingId = $Model->{$this->habtmModel}->id;
} else {
$existingId = $existingRecord[$this->habtmModel][ClassRegistry::init($this->habtmModel)->primaryKey];
}
return $existingId;
}
private function buildCondition(&$Model) {
foreach($Model->{$this->habtmModel}->schema() as $field => $type) {
$conditions[] = array($Model->{$this->habtmModel}->name . '.' . $field => $Model->data[$this->habtmModel][$field]);
}
}
}
return $conditions;
}
}
?> |
