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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 21:38:08  来源:igfitidea点击:

Update only one field on Cakephp 3

phpcakephp-3.0

提问by Daniel Faria

In some part of my app I need to update only the field is_activeof some tablewith 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_heretable with a new value for is_activecolumn.

使用此处的示例: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));
}