CakePHP 3.x:从一个表单到多个表的多个记录

时间:2016-01-07 09:22:29

标签: cakephp cakephp-3.0

我想将一个表单中的记录填充到几个表中,但我找不到任何解决方案。你能给我一个小例子吗?

Bake为我创建了这段代码。

表:

$this->table('order');
        $this->displayField('name');
        $this->primaryKey('id');

        $this->belongsTo('Clients', [
            'foreignKey' => 'client_id',
            'joinType' => 'INNER'
        ]);

控制器:

 $order = $this->Orders->newEntity();
                if ($this->request->is('post')) {
                    $order = $this->Order->patchEntity($order, $this->request->data);
                    if ($this->Orders->save($order)) {
                       $this->Flash->success(__('Order has been saved.'));
                       return $this->redirect(['action' => 'index']);
                    } else {
                      $this->Flash->error(__('Try again.'));
                    }
                }

        $clients = $this->Orders->Clients->find('list', ['limit' => 200]);  
        $this->set(compact('order', 'clients'));
        $this->set('_serialize', ['order']);

模板:

$this->Form->create($order)
echo $this->Form->input('number', array('label' => ('Number')));
/** more inputs **/

$this->Form->create($client)
echo $this->Form->input('name');
/** more inputs **/

$this->Form->button(__('Submit');
$this->Form->end();

提前致谢。

1 个答案:

答案 0 :(得分:1)

如文档(link

中所述
$this->Form->create($order)
echo $this->Form->input('number', array('label' => ('Number')));
/** more inputs **/

echo $this->Form->input('client.name');
/** more inputs **/

$this->Form->button(__('Submit');
$this->Form->end();

然后在您的控制器中

$order = $this->Orders->patchEntity(
    $order, 
    $this->request->data,
    [
        'associated' => ['Clients']
    ]
);

请注意,您的代码中有错误,可能只是一个错字,但是:$this->Orders->patchEntity而不是$this->Order->patchEntity。模型必须是复数