Bin will be removed on June 1, 2014 in favor of http://gist.github.com. Please save all your pastes before then. So long, and thanks for all the fish!×
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
   private $fieldsToSkip = array('id', 'created', 'modified', 'updated');
   
   //holds name of the related model
   private $habtmModel;
   
   public function setup(&$Model, $settings = array()) {
    if(empty($settings)) {    
      $this->settings['habtmModel'] = key($Model->hasAndBelongsToMany);
    }
   
    $this->habtmModel = $this->settings['habtmModel'];  
  }
   
   public function beforeSave(&$Model) {
                       
      $existingId = $this->getExistingId(&$Model);
     
      if(!empty($existingId)) {
        $Model->data[$this->habtmModel][$this->habtmModel] = $existingId;
      }
           
    return TRUE;
  }
 
  private function getExistingId(&$Model) {
   $conditions = $this->buildCondition($Model);
   
   $existingRecord = $Model->{$this->habtmModel}->find('first', array('conditions' => $conditions,
                                                                      '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) {
     
      if(!in_array($field, $this->fieldsToSkip)) {
        if(isset($Model->data[$this->habtmModel][$field])) {          
          $conditions[] = array($Model->{$this->habtmModel}->name . '.' . $field => $Model->data[$this->habtmModel][$field]);  
        }
      }  
    }  
   
    return $conditions;
  }
     
}
?>