Пример #1
0
 /**
  * 
  * Saves the related "through" collection *and* the foreign collection
  * from a native record.
  * 
  * Ensures the "through" collection has an entry for each foreign record,
  * and adds/removes entried in the "through" collection as needed.
  * 
  * @param Solar_Sql_Model_Record $native The native record to save from.
  * 
  * @return void
  * 
  */
 public function save($native)
 {
     // get the foreign collection to work with
     $foreign = $native->{$this->name};
     // get the through collection to work with
     $through = $native->{$this->through};
     // if no foreign, and no through, we're done
     if (!$foreign && !$through) {
         return;
     }
     // if no foreign records, kill off all through records
     if (!$foreign) {
         $through->deleteAll();
         return;
     }
     // save the foreign records as they are, which creates the necessary
     // primary key values the through mapping will need
     $foreign->save();
     // we need a through mapping
     if (!$through) {
         // make a new collection
         $through = $native->newRelated($this->through);
         $native->{$this->through} = $through;
     }
     // the list of existing foreign values
     $foreign_list = $foreign->getColVals($this->foreign_col);
     // the list of existing through values
     $through_list = $through->getColVals($this->through_foreign_col);
     // find mappings that *do* exist but shouldn't, and delete them
     foreach ($through_list as $through_key => $through_val) {
         if (!in_array($through_val, $foreign_list)) {
             $through->deleteOne($through_key);
         }
     }
     // make sure all existing "through" have the right native IDs on the
     foreach ($through as $record) {
         $record->{$this->through_native_col} = $native->{$this->native_col};
     }
     // find mappings that *don't* exist, and add them
     foreach ($foreign_list as $foreign_val) {
         if (!in_array($foreign_val, $through_list)) {
             $through->appendNew(array($this->through_native_col => $native->{$this->native_col}, $this->through_foreign_col => $foreign_val));
         }
     }
     // done with the mappings, save them
     $through->save();
 }