【问题标题】:Saving Array CakePhp保存数组 CakePhp
【发布时间】:2015-06-08 13:44:01
【问题描述】:

我想将数组中的值保存到数据库的一个字段中。我一直在使用该代码,但没有保存任何内容。

$this->Form->input('Model.0.field1');
$this->Form->input('Model.0.field2');
$this->Form->input('Model.1.field1');
$this->Form->input('Model.1.field2');

谢谢。

【问题讨论】:

  • 您尝试使用的保存代码在哪里?您使用的是哪个版本的 CakePHP(它有很大的不同)。官方文档详细介绍了如何保存,因此请确保您已正确阅读!
  • 嘿!是的,我已经阅读了它并遵循了每一步,但没有保存任何内容:/!我正在使用 CakePhp 2.6.0 。我有一个 HABTM 关联,​​我的保存代码在关联控制器中。
  • 请将您在控制器中使用的代码添加到问题中以保存。表单输入并没有真正提供有关您正在尝试什么或出了什么问题的足够信息。
  • 如果您真的想将此数组存储到一个数据库字段中,您可以json_encode($this->request->data['Model']),然后您可以在需要时轻松json_decode($value, true); 将其返回。

标签: arrays cakephp cakephp-2.6


【解决方案1】:

我认为您需要使用 json_encode() 值保存数据。

// In your controller

public function test() {

    if($this->request->is('post'))   {

        //If you want to insert in single row then you can use json_encode() and add to your colum.

        $insert_data = json_encode($this->request->data);

        $data = array(); 
        // Load your model where you want save data

        $this->loadModel('Test'); 
        // set attribute name where you want to save

        $data['Test']['value'] = $insert_data; 
        $this->Test->save($data);

        //For viewing your data
        $fetchedData = $this->Test->find('all');
        foreach($fetchedData as $items) {
            var_dump(json_decode($items['Test']['value']));
        }
    }   
}

您可以使用 implode() 生成逗号分隔的数据。如果要使用implode(),请看Inserting an array into a mysql database column

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-14
    • 2013-09-24
    • 2012-08-08
    • 2010-12-18
    相关资源
    最近更新 更多