我有两个模型(或Cakephp 3中的表格),其中一个是部门,另一个是经理,我做了一个' hasOne&#39 ;这两者之间的联系:
部门表(数据库):
------------------------
| 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);
}
}
当我在填写表单后尝试提交表单时,两个新部门的部门&#39;和经理&#39;已经成功添加,但新的“经理”排除了#39;有值&#39; NULL&#39; on&#39; department_id&#39;列而不是新部门的ID值#39;最近创建了一行。
拜托,有谁可以帮我解决这个问题?
答案 0 :(得分:2)
关系类型应为belongsTo()
作为一般规则,您可以知道何时使用belongsTo或hasOne: