Saving and deleting
To add a row to a table you create an entity object, fill its fields and hand it to the table for saving. Changing and deleting work the same way: the record is fetched first and then given to the table.
Creating a record
// src/Controller/ArticlesController.php
public function demo()
{
$article = $this->Articles->newEmptyEntity();
$article->title = 'New article';
$article->body = 'Article text.';
$this->Articles->save($article);
return $this->redirect(['action' => 'index']);
}newEmptyEntity() creates an empty entity and save() adds it to the table. Open /articles/demo: you return to the list and the new article is there. The id, created and modified columns were filled in automatically.
Data from an array
Form data arrives as an array. The patchEntity() method moves it into an entity:
$article = $this->Articles->newEmptyEntity();
$article = $this->Articles->patchEntity($article, [
'title' => 'Article from an array',
'body' => 'Article text.',
]);
$this->Articles->save($article);patchEntity() fills only the fields allowed in $_accessible of the entity class and validates the data along the way. The array is usually $this->request->getData().
The result of saving
if ($this->Articles->save($article)) {
// the record is saved, its number is $article->id
} else {
debug($article->getErrors());
}save() returns the entity on success and false when the data did not pass validation. The reasons are in getErrors(). The saveOrFail() method throws an exception instead of returning false.
Changing
$article = $this->Articles->get(1);
$article->title = 'New title';
$this->Articles->save($article);The same save() sees that the record already exists in the database and updates it. Only changed fields are sent.
Deleting
$article = $this->Articles->get(1);
$this->Articles->delete($article);delete() returns true when the record is deleted.
Several records with one query
| Call | What it does |
|---|---|
updateAll(['published' => false], ['views' => 0]) | Changes fields of all matching records |
deleteAll(['published' => false]) | Deletes all matching records |
The first argument of updateAll() holds new values and the second is a condition, as in where(). These methods create no objects and run no validation.
Common mistake
A field not listed in $_accessible is silently skipped by patchEntity(), so a visitor cannot slip someone else's user_id into a form. But when a new form field "does not save", the reason is almost always here. Add the field to $_accessible in src/Model/Entity/Article.php instead of opening everything with '*' => true.