I’m trying to update only one piece of information from a user saved in the database, and cakephp accepts an array of values for each attribute, but I don’t have values for other attributes and cakephp will not update the row because it is expecting all the values found in the row.
Advertisement
Answer
First Way : Create new a Query object using query():
$users = TableRegistry::get('Users'); $query = $users->query(); $query->update() ->set(['is_active' => true]) ->where(['id' => $id]) ->execute();
Second Way: Using PatchEntity
using the fieldList() option when creating or merging data into an entity:
this will allow you to only update or insert field u want
$user = $this->Users->get($id); if ($this->request->is(['post', 'put'])) { //assume $this->request->data Contains field as ['name' => 'myname', 'title' => 'Hacked!']; $user = $this->Users->patchEntity($user, $this->request->data, [ 'fieldList' => ['title']]); // Only allow title to be changed if ($this->Users->save($user)) { $this->Flash->success(__('Your user has been updated.')); return $this->redirect(['action' => 'index']); } $this->Flash->error(__('Unable to update your user.')); }
http://book.cakephp.org/3.0/en/orm/saving-data.html#changing-accessible-fields
http://book.cakephp.org/3.0/en/orm/query-builder.html#updating-data