我在使用hasMany關聯保存數據時遇到了問題。有兩個 表像波紋管。現在,當我保存它時,它僅保存數據 服務表,但它不保存到service_times表。我在這裏給出了 模板和控制器代碼。任何人都可以建議我, 我該如何解決這個問題。如何在CakePHP 3.x中保存HasMany關聯數據
1) services table:
id | id | ...
1 | name | ...
2) service_times table
id | id | ...
1 | service_id | ...
2 | star_time | (type= time)
3 | end_time | (type= time)
模板表單:
<?= $this->Form->create($service) ?>
<fieldset>
<legend><?= __('Add Service') ?></legend>
<?php
echo $this->Form->input('name');
echo $this->Form->input('ServiceTimes.start_time');
echo $this->Form->input('ServiceTimes.end_time');
echo $this->Form->input('description');
?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
服務控制器
public function add(){
$service = $this->Services->newEntity($this->request->data, [
'associated' => ['ServiceTimes']
]);
if ($this->request->is('post')) {
if ($this->Services->save($service, ['associated' => ['ServiceTimes']])) {
pr($this->request->data);exit;
$this->Flash->success(__('The service has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The service could not be saved. Please, try again.'));
}
}
//}
$this->set(compact('service'));
$this->set('_serialize', ['service']);
$this->viewBuilder()->theme('ThemeAdmin');
}
我建議有一個看文檔到掌握相關數據如何構建以便妥善保存。 ** http://book.cakephp.org/3.0/en/views/helpers/form.html#creating-inputs-for-associated-data** | ** http://book.cakephp.org/3.0/en/orm/saving-data.html#saving-hasmany-associations** – ndm