【问题标题】:How to update multiple rows of a model?如何更新模型的多行?
【发布时间】:2018-02-28 08:13:07
【问题描述】:

我想一次更新特定模型的多行,所以我有下面的代码和数据结构。每当我尝试在每次插入记录而不是更新时更新记录。

在我的控制器中

function products($cat_id = null){
   $products = $this->Products->find()->where(['category_id' => $cat_id]);

   $productPatch = $this->Products->patchEntities($products, $this->request->data);

   $this->Products->saveMany($productPatch);     //Always creates new record
}

这是不同数组中的数据,

In $products  
   [0] => Array
        (
            [id] => 13              //product_id
            [category_id] => 17
            [slug] => onScreen
            [status_id] => 1
        )

    [1] => Array
        (
            [id] => 14
            [category_id] => 17
            [slug] => pdf
            [status_id] => 1
        )

In $this->request->data


  [0] => Array
    (
        [id] => 13              //product_id
        [category_id] => 17
        [slug] => onScreen
        [status_id] => 2          //Data changes here
    )

    [1] => Array
        (
            [id] => 14
            [category_id] => 17
            [slug] => pdf
            [status_id] => 2          //Data changes here
        )

【问题讨论】:

  • $products 应该是一个实体数组...还有debug($productPatch) 以检查可能存在的问题。
  • 忘了说 $products 是一个实体数组,只有更好的可视性和数据格式我已经通过转换成数组来打印代码。 @ndm
  • 为了更好地指导我,当我打印 $products 时,我在每个数组中找到了 id 索引,但是在 patchEntities 之后,我没有在数组中找到 id,我知道这是问题但无法理解是什么导致了这个问题:(@ndm
  • 可能有很多原因,没有看到全图我只能在黑暗中拍摄,这并不过分帮助。您必须进行一些调试,也许在修补之前修改了数据(beforeMarshal),也许您有一些自定义实体或表(查找器)逻辑导致了这种情况,也许您在保存后正在调试并且出现问题保存阶段,如应用程序规则、beforeSave 处理程序等...如果您显示调试结果可能会有所帮助。

标签: cakephp cakephp-3.0 cakephp-3.2


【解决方案1】:

您可以使用 updateAll() 方法批量更新数据:

$this->modelClass->updateAll(
    ['published' => true], // fields
    ['published' => false]); // conditions

【讨论】:

    猜你喜欢
    • 2020-06-22
    • 2020-08-19
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-18
    相关资源
    最近更新 更多