Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Sync a many to many record to an entity
- * https://laravel.com/docs/4.2/eloquent#inserting-related-models
- *
- * Usage:
- * $entity->sync('alias_name', array(1, 2, 3), $transaction);
- * @param $related_alias string Many to Many alias name
- * @param $identifiers array array of ID's of the related records
- * @param $transaction object Phalcon Trancation object if the entity is part of a transaction
- * @return true | Exception
- */
- public function sync($related_alias, array $identifiers, \Phalcon\Mvc\Model\Transaction $transaction = NULL) {
- $modelsmanager = $this->getDI()->getModelsManager();
- $relation = $modelsmanager->getRelationByAlias(get_class($this), $related_alias);
- if(!$relation) {
- $msg = sprintf('Relation alias "%s" does not exists', $related_alias);
- if($transaction) {
- $transaction->rollback($msg);
- } else {
- throw new \Exception($msg);
- }
- }
- $related_ids = array();
- $existing_ids = array();
- $new_ids = array();
- $related = $this->getRelated($related_alias);
- foreach($related as $r) {
- array_push($related_ids, $r->id);
- }
- foreach($identifiers as $i) {
- if(!in_array($i, $related_ids)) {
- array_push($new_ids, $i);
- } else {
- array_push($existing_ids, $i);
- }
- }
- $delete_ids = array_diff($related_ids, array_merge($existing_ids, $new_ids));
- $intermediate_model = $relation->getIntermediateModel();
- foreach($new_ids as $related_id) {
- $intermediate = new $intermediate_model;
- if($transaction) {
- $intermediate->setTransaction($transaction);
- }
- $intermediate->{$relation->getIntermediateFields()} = $this->id;
- $intermediate->{$relation->getIntermediateReferencedFields()} = $related_id;
- if($intermediate->create() == false) {
- $msg = 'Could not create intermediate record: ';
- foreach($intermediate->getMessages() as $m) {
- $msg .= $m;
- }
- if($transaction) {
- $transaction->rollback($msg);
- } else {
- throw new \Exception($msg);
- }
- }
- }
- foreach($delete_ids as $related_id) {
- $intermediate = $intermediate_model::findFirst(array(
- $relation->getIntermediateFields().' = ?0 AND '.$relation->getIntermediateReferencedFields().' = ?1',
- 'bind' => array(
- 0 => $this->id,
- 1 => $related_id
- )
- ));
- if($intermediate) {
- if($transaction) {
- $intermediate->setTransaction($transaction);
- }
- if($intermediate->delete() == false) {
- $msg = 'Could not delete intermediate record: ';
- foreach($intermediate->getMessages() as $m) {
- $msg .= $m;
- }
- if($transaction) {
- $transaction->rollback($msg);
- } else {
- throw new \Exception($msg);
- }
- }
- }
- }
- return true;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement