dongxun6690 2011-06-09 17:17
浏览 25
已采纳

使用CakePHP更新数组中的字段

I have an array that is sent to my controller, such as this:

$array = array(
        [0]=>array(
             [id]=>5,
             [position]=>6 
        ),
       [1]=>array(
             [id]=>8,
             [position]=>2 
        )
);

And I need to save the position of each item using its id. What is the best way to do this in cakePHP? I can only imagine looping an update function or pulling the entire database, changing the correct values, then saving the database. Both ideas seem very bodged.

  • 写回答

2条回答 默认 最新

  • doudongdang4483 2011-06-09 17:40
    关注

    Ha, Cake magic to the rescue again. You don't have to tell Cake to save it by id. There's a big long amazing way Cake does this, but the short and skinny is -

    if your array contains an 'id' key, Cake presumes it is the table primary key and generates an UPDATE statement instead of an INSERT. Looks like this:

    UPDATE table as Table SET Table.position = $position WHERE Table.id = $id;
    

    And, Cake knows to iterate for you if you use saveAll() instead of save():

    $this->Model->saveAll($array);
    

    If you have any save callbacks in your model, such as beforeSave(), you have to call them manually before calling saveAll() - they only autofire on save(), not saveAll() or updateAll().

    You'll want to top your array with the name of your model ($array['Model'][0], $array['Model'][1], etc). If you need to magically saveAll() with multiple models, you top your array with indexed keys, then model names - like $array[0]['Model1'], $array[0]['Model2']) and Cake knows to save / update the associated data for all the models in each index batch.

    Cake does ALL the legwork for you:

    http://book.cakephp.org/view/1031/Saving-Your-Data - especially the saveAll() entry.

    • Edit - and topping your array with your model name? Cake makes that ridiculously easy, too. Check out Cake's built-in Set library for all your array / object manipulation needs.

    http://book.cakephp.org/view/1487/Set

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型