这实际上是延续 CakePHP 3 - Users belongsToMany Users
我不知道如何正确实施保存程序。
而不是用户我有机构。一个机构可以被另一个机构兼并。所以我需要一个自引用模型。
我想使用下拉菜单添加(或删除)附属机构,如下所示:
这是我到目前为止所做的:
InstitutionsTable.php
$this->hasMany('ConnectionsTo', [
'className' => 'Connections',
'foreignKey' => 'institution_id'
]);
$this->hasMany('ConnectionsFrom', [
'className' => 'Connections',
'foreignKey' => 'id'
]);
ConnectionsTable.php
$this->belongsTo('InstitutionsTo', [
'className' => 'Institutions',
'foreignKey' => 'id',
'joinType' => 'INNER'
]);
$this->belongsTo('InstitutionsFrom', [
'className' => 'Institutions',
'foreignKey' => 'institution_id',
'joinType' => 'INNER'
]);
InstitutionsController.php
public function edit($id = null)
{
$institutions = $this->Institutions->get($id, [
'contain' => ['ConnectionsFrom.InstitutionsFrom','ConnectionsTo.InstitutionsTo']
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$institutions = $this->Institutions->patchEntity($institutions, $this->request->getData(),[
'associated' => ['ConnectionsFrom.InstitutionsFrom','ConnectionsTo.InstitutionsTo']
]);
if ($this->Institutions->save($institutions)) {
$this->Flash->success(__('The institution has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The institution could not be saved. Please, try again.'));
}
$instList = $this->Institutions->find('list');
$this->set(compact('institutions', 'instList'));
$this->set('_serialize', ['institutions']);
}
部分调试$ this-> request-> getData()
注意:这是保存控件/选择值的属性。
'ConnectionsFrom' => [
'InstitutionsFrom' => '1'
],
...
$ institutions的部分调试
注意:这是通过' contains'加载的属性。我在DB中手动添加了一些条目以测试正确的实现。
'connections_from' => [
(int) 0 => object(App\Model\Entity\Connection) {
'id' => (int) 42,
'institution_id' => (int) 17,
'institutions_from' => object(App\Model\Entity\Institution) {
'id' => (int) 17,
...
edit.ctp
echo $this->Form->control('ConnectionsFrom.InstitutionsFrom',['options' => $instList]);
主要问题是:
我有一个属性,我可以从下拉值中保存所有机构ID。但我有一个第二个属性,它包含App \ Model \ Entity \ Institution类型的对象,我不知道如何合并它们。我(或蛋糕)必须保存类型为" Connection"的对象。不是从此属性的下拉列表中的整数值。
现在,我使用query() - > update()作为解决方法直接写入数据库。但我想要蛋糕方式。那么,我有什么要告诉Cake正确保存/补丁?