php 仅更新 Cakephp 3 上的一个字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30218488/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Update only one field on Cakephp 3
提问by Daniel Faria
In some part of my app I need to update only the field is_active
of some table
with a lot of fields. What is the best approach to update only this field and avoid the validations and requiriments of all other fields?
在我的应用程序的某些部分,我只需要更新具有很多字段is_active
的某些table
字段。仅更新此字段并避免所有其他字段的验证和要求的最佳方法是什么?
回答by Manohar Khadka
And if you want to update particular row only , use this:
如果您只想更新特定行,请使用以下命令:
$users= TableRegistry::get('Users');
$user = $users->get($id); // Return article with id = $id (primary_key of row which need to get updated)
$user->is_active = true;
// $user->email= [email protected]; // other fields if necessary
if($users->save($user)){
// saved
} else {
// something went wrong
}
See here (Updating data in CakePHP3).
请参阅此处(在 CakePHP3 中更新数据)。
回答by Isaac Askew
This will work:
这将起作用:
$users = TableRegistry::get('Users');
$query = $users->query();
$query->update()
->set(['is_active' => true])
->where(['id' => $id])
->execute();
http://book.cakephp.org/3.0/en/orm/query-builder.html#updating-data
http://book.cakephp.org/3.0/en/orm/query-builder.html#updating-data
回答by Yasen Zhelev
Using the example here: http://book.cakephp.org/3.0/en/orm/database-basics.html#running-update-statements. Run the code below to update all records in table_name_here
table with a new value for is_active
column.
使用此处的示例:http: //book.cakephp.org/3.0/en/orm/database-basics.html#running-update-statements。运行下面的代码以table_name_here
使用新的is_active
列值更新表中的所有记录。
use Cake\Datasource\ConnectionManager;
$connection = ConnectionManager::get('default');
$connection->update('table_name_here', ['is_active' => 'new_value_here']);
回答by omid
When you don't want callbacks to be triggered, just use updateAll()
当您不想触发回调时,只需使用 updateAll()
$table->updateAll(['field' => $newValue], ['id' => $entityId]);
回答by Kwaadpepper
The other answers don't use internationalization and other models props, callbacks, etc. I think this is because of the query builder, it does not use the models and so their behaviors, therefore you should use:
其他答案不使用国际化和其他模型道具、回调等。我认为这是因为查询构建器,它不使用模型及其行为,因此您应该使用:
$this->loadModel('Inputs');
$input = $this->Inputs->find()->where(['`key`' => $this->request->data['id']])->first();
$this->Inputs->patchEntity($input, ['prop' => $this->request->data['prop']]);
if ($this->Inputs->save($input)) {
die(json_encode(true));
} else {
die(json_encode(false));
}