尝试从多个select中保存hasMany数组

时间:2013-04-10 21:48:35

标签: php arrays cakephp cakephp-2.0

我正在尝试从多个选择中保存数据。这个数据被重新关联,其中“请求”有多个“Requestc”。 foriegnKey是“request_id”

我的控制器:

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

    $solicitacao = $this->Request->save($this->request->data['Request']);

    //Verifica se a request foi salva e se sim, salva quais as certidões foram pedidas na tabela requests_certidoes
    if(!empty($solicitacao)) {
        $this->request->data['Requestc']['request_id'] = $this->Request->id;
    //  debug($this->request->data);

        $this->Request->Requestc->saveAll($this->request->data);
    }
}

这是我$this->request->data的数据:

array(
'Request' => array(
    'motivo' => 'Licitação',
    'nome_licitacao' => '',
    'data_pregao' => '',
    'nome_cliente' => '',
    'outros' => ''
),
'Requestc' => array(
    'caminho' => array(
        (int) 0 => '1',
        (int) 1 => '3'
    ),
    'request_id' => '60'
)

这就是错误:

错误:SQLSTATE [42S22]:未找到列:1054'字段列表'中的未知列'数组'

SQL查询:INSERT INTO societariorequests_certidoescaminhorequest_id)VALUES(数组,62)

全部谢谢

1 个答案:

答案 0 :(得分:2)

您需要修改发布的数据,使其如下所示:

array(
    'Request' => array(
        'motivo' => 'Licitação',
        'nome_licitacao' => '',
        'data_pregao' => '',
        'nome_cliente' => '',
        'outros' => ''
    ),
    'Requestc' => array(
        0 => array(
            'caminho' => '1',
            // --> optionally add your request_id here
            //     if you're manually saving Requestc
            //     AFTER saving Request
        ),
        1 => array(
            'caminho' => '3',
        )
    )
)

如果您的关系设置正确,您可能不必添加request_id;

$data = array(
    'Request' => $this->request->data['Request'],
    'Requestc' => array();
);

foreach($this->request->data['Requestc']['caminho'] as $val) {
    $data['Requestc'][] = array(
        'caminho' => $val,

        // Should NOT be nescessary when using the saveAssociated()
        // as below
        //'request_id' => $this->Request->id;
    );
}

// This should insert both the Request *and* the Requestc records
$this->Request->saveAssociated($data);

请参阅文档:Saving Related Model Data (hasOne, hasMany, belongsTo)

但是,如果Requestc.caminho存储id的{​​{1}},则这似乎是HABTM关系; Certificates,在这种情况下,联接表应调用Request --> HABTM --> Certificate并包含certificates_requestsrequest_id列。请参阅Model and Database Conventions