0
我有兩個模型(或表在CakePHP 3),其中之一是部,另一個是經理,我做了這兩個之間的「hasOne協會:保存在CakePHP中hasOne協會3
部門表(數據庫):
------------------------
| id | name | location |
------------------------
| 1 | IT | New York |
------------------------
管理表(數據庫):
-----------------------------------------
| id | name | address | department_id |
-----------------------------------------
| 1 | Mike | New York | 1 |
-----------------------------------------
DepartmentsTable.php
<?php
namespace App\Model\Table;
use Cake\ORM\Table;
use Cake\Validation\Validator;
class DepartmentsTable extends Table {
public function initialize(array $config){
}
}
ManagersTable.php
<?php
namespace App\Model\Table;
use Cake\ORM\Table;
use Cake\Validation\Validator;
class ManagersTable extends Table {
public function initialize(array $config){
$this->hasOne('Departments');
}
}
我創建了一個表格,以便我能救一個人有他的地址:
<?php echo $this->Form->create($manager); ?>
<?php echo $this->Form->input('Manager.name'); ?>
<?php echo $this->Form->input('Manager.address'); ?>
<?php echo $this->Form->input('Manager.department.name'); ?>
<?php echo $this->Form->input('Manager.department.location'); ?>
<?php echo $this->Form->end('valider'); ?>
,這是控制器:
<?php
namespace App\Controller\Adminocity;
use App\Controller\AppController;
use Cake\Core\Configure;
use Cake\Network\Exception\NotFoundException;
use Cake\View\Exception\MissingTemplateException;
use Cake\Cache\Cache;
use Cake\ORM\TableRegistry;
use Cake\Event\Event;
class ManagersController extends AppController {
public function edit_manager($id=null)
{
$this->loadModel('Departments');
$manager = $this->Managers->newEntity();
if($this->request->is('post')){
$managersTable = TableRegistry::get('Managers');
$manager = $managersTable->patchEntity($manager,$this->request->data(), ['associated' => ['Departments']]);
if($managersTable->save($manager)){
$this->Flash->success(__('Manager ajouté avec succès'));
return $this->redirect(['action' => 'list_managers']);
}
}
$this->set('manager', $manager);
}
}
當我嘗試t o在填寫完表單後提交表單,'Department'和'Manager'的新行成功添加,但'Manager'的新行在'department_id'列上的值爲'NULL',而不是id的值最近創建的新「部門」行。
請問誰能幫我解決這個問題?
謝謝,這幫了很大忙 –