delete() public method

For HasMany and HasOne associations records will be removed based on the dependent option. Join table records in BelongsToMany associations will always be removed. You can use the cascadeCallbacks option when defining associations to change how associated data is deleted. ### Options - atomic Defaults to true. When true the deletion happens within a transaction. - checkRules Defaults to true. Check deletion rules before deleting the record. ### Events - Model.beforeDelete Fired before the delete occurs. If stopped the delete will be aborted. Receives the event, entity, and options. - Model.afterDelete Fired after the delete has been successful. Receives the event, entity, and options. - Model.afterDeleteCommit Fired after the transaction is committed for an atomic delete. Receives the event, entity, and options. The options argument will be converted into an \ArrayObject instance for the duration of the callbacks, this allows listeners to modify the options used in the delete operation.
public delete ( Cake\Datasource\EntityInterface $entity, $options = [] )
$entity Cake\Datasource\EntityInterface
Example #1
0
 /**
  * Removes all links between the passed source entity and each of the provided
  * target entities. This method assumes that all passed objects are already persisted
  * in the database and that each of them contain a primary key value.
  *
  * ### Options
  *
  * Additionally to the default options accepted by `Table::delete()`, the following
  * keys are supported:
  *
  * - cleanProperty: Whether or not to remove all the objects in `$targetEntities` that
  * are stored in `$sourceEntity` (default: true)
  *
  * By default this method will unset each of the entity objects stored inside the
  * source entity.
  *
  * ### Example:
  *
  * ```
  * $article->tags = [$tag1, $tag2, $tag3, $tag4];
  * $tags = [$tag1, $tag2, $tag3];
  * $articles->association('tags')->unlink($article, $tags);
  * ```
  *
  * `$article->get('tags')` will contain only `[$tag4]` after deleting in the database
  *
  * @param \Cake\Datasource\EntityInterface $sourceEntity an entity persisted in the source table for
  * this association
  * @param array $targetEntities list of entities persisted in the target table for
  * this association
  * @param array|bool $options list of options to be passed to the internal `delete` call,
  * or a `boolean`
  * @throws \InvalidArgumentException if non persisted entities are passed or if
  * any of them is lacking a primary key value
  * @return void
  */
 public function unlink(EntityInterface $sourceEntity, array $targetEntities, $options = [])
 {
     if (is_bool($options)) {
         $options = ['cleanProperty' => $options];
     } else {
         $options += ['cleanProperty' => true];
     }
     $this->_checkPersistenceStatus($sourceEntity, $targetEntities);
     $property = $this->property();
     $this->junction()->connection()->transactional(function () use($sourceEntity, $targetEntities, $options) {
         $links = $this->_collectJointEntities($sourceEntity, $targetEntities);
         foreach ($links as $entity) {
             $this->_junctionTable->delete($entity, $options);
         }
     });
     $existing = $sourceEntity->get($property) ?: [];
     if (!$options['cleanProperty'] || empty($existing)) {
         return;
     }
     $storage = new SplObjectStorage();
     foreach ($targetEntities as $e) {
         $storage->attach($e);
     }
     foreach ($existing as $k => $e) {
         if ($storage->contains($e)) {
             unset($existing[$k]);
         }
     }
     $sourceEntity->set($property, array_values($existing));
     $sourceEntity->dirty($property, false);
 }
Example #2
0
 public function deleteCronAction()
 {
     $id = $_POST['id'] ?? null;
     if ($id) {
         try {
             $cron = $this->cronsTable->get($id);
             if (($_POST['deleteLog'] ?? false) == $id && $cron->output) {
                 $logFile = $this->site['logFolder'] . '/' . $cron->output;
                 if (!unlink($logFile)) {
                     $this->flasher->error("Could not delete log file: " . $logFile);
                 }
             }
             $this->cronsTable->delete($cron);
             $this->flasher->success('Successfully deleted cron!');
         } catch (\Exception $e) {
             $this->flasher->error("Could not delete cron: " . $e->getMessage());
         }
         $this->redirect('/admin/crons');
     }
 }
 /**
  * Deletes an user record
  *
  * @param mixed $userId
  * @param array $options
  * @return boolean
  */
 public function deleteUser($userId = null, $options = [])
 {
     $entity = $this->_getUserEntity($userId);
     if ($this->UserTable->delete($entity)) {
         $this->handleFlashAndRedirect('success', $options);
         return true;
     } else {
         $this->handleFlashAndRedirect('error', $options);
         return false;
     }
 }
 /**
  * Deletes an user record
  *
  * @param mixed $userId
  * @param array $options
  * @return boolean
  */
 public function deleteUser($userId = null, $options = [])
 {
     if (is_string($userId) || is_integer($userId)) {
         $entity = $this->UserTable->newEntity([$this->UserTable->primaryKey() => $userId]);
     }
     if (is_array($userId)) {
         $entity = $this->UserTable->newEntity($userId);
     }
     if ($this->UserTable->delete($entity)) {
         $this->handleFlashAndRedirect('success', $options);
         return true;
     } else {
         $this->handleFlashAndRedirect('error', $options);
         return false;
     }
 }
Example #5
0
 /**
  * Implementation of the beforeSave event, handles uploading / saving and overwriting of image records.
  *
  * @param Event $event Event object.
  * @param Entity $entity Entity object.
  * @param \ArrayObject $options Options array.
  * @return void
  */
 public function beforeSave(Event $event, Entity $entity, \ArrayObject $options)
 {
     $fields = $this->config('fields');
     $alias = $this->_table->alias();
     $options['associated'] = [$this->_imagesTable->alias() => ['validate' => false]] + $options['associated'];
     $entities = [];
     foreach ($fields as $fieldName => $fieldType) {
         $uploadedImages = [];
         $field = $entity->get($fieldName);
         $field = $fieldType == 'one' ? [$field] : $field;
         foreach ($field as $image) {
             $result = array();
             if (!empty($image['tmp_name'])) {
                 $result = $this->_upload($image['name'], $image['tmp_name'], false);
             } elseif (is_string($image)) {
                 $result = $this->_upload($image, $image, true);
             }
             if (!empty($result)) {
                 $uploadedImages[] = $result + ['model' => $alias, 'field' => $fieldName];
             }
         }
         if (!empty($uploadedImages)) {
             if (!$entity->isNew() && $fieldType == 'one') {
                 $preexisting = $this->_imagesTable->find()->where(['model' => $alias, 'field' => $fieldName, 'foreign_key' => $entity->id])->bufferResults(false);
                 foreach ($preexisting as $index => $image) {
                     $this->_imagesTable->delete($image);
                 }
             }
             foreach ($uploadedImages as $image) {
                 $entities[] = $this->_imagesTable->newEntity($image);
             }
         }
         $entity->dirty($fieldName, true);
     }
     $entity->set('_images', $entities);
 }
Example #6
0
 /**
  * Method called on the destruction of a database session.
  *
  * @param int $id ID that uniquely identifies session in database
  * @return bool True for successful delete, false otherwise.
  */
 public function destroy($id)
 {
     return (bool) $this->_table->delete(new Entity([$this->_table->primaryKey() => $id], ['markNew' => false]));
 }
Example #7
0
 /**
  * {@inheritDoc}
  *
  * Additional options
  * - 'strict': Throw exception instead of returning false. Defaults to false.
  */
 public function delete(EntityInterface $entity, $options = [])
 {
     $options += ['strict' => false];
     $result = parent::delete($entity, $options);
     if ($result === false && $options['strict'] === true) {
         throw new InvalidArgumentException('Could not delete ' . $entity->source() . ': ' . print_r($entity->id, true));
     }
     return $result;
 }
 /**
  * Method called on the destruction of a database session.
  *
  * @param int $id ID that uniquely identifies session in database
  * @return bool True for successful delete, false otherwise.
  */
 public function destroy($id)
 {
     return $this->_table->delete(new Entity([$this->_table->primaryKey() => $id]));
 }