3
我想將多個遊戲關聯到數據庫中的連續性。在Cakephp 3中使用BelongsToMany關聯
我有3個表格:continuities,continuities_games和games。 continuities_games表有一個continuity_id和一個game_id。當我嘗試在我的選擇輸入中選擇不同的遊戲時,它會在數據庫中創建一個新的遊戲入口,然後在連接表中創建一個條目,將其鏈接到新的遊戲條目,而不是將其鏈接到最初選擇的遊戲。
這是我ContinuitiesTable初始化函數:
public function initialize(array $config){
parent::initialize($config);
$this->belongsToMany('Games');
}
而對於我GamesTable:
public function initialize(array $config){
parent::initialize($config);
$this->displayField('name');
$this->addBehavior('Tree');
//Associations
$this->hasMany('Children', [
'className' => 'Games',
'foreignKey' => 'parent_id',
'dependant' => true,
'cascadeCallbacks' => true,
]);
$this->belongsTo('Parent', [
'className' => 'Games',
]);
$this->hasMany('Books');
$this->belongsToMany('Continuities');
}
這是ContinuitiesController我的編輯功能:
public function edit($id=null){
$continuity = $this->Continuities->find()->where(['id'=>$id])->contain('Games')->first();
if ($this->request->is(['post', 'put'])) {
debug($this->request->data);
$continuity->start_date = $this->request->data['start_date']['year'].'-'.$this->request->data['start_date']['month'].'-'.$this->request->data['start_date']['day'];
$continuity->end_date = $this->request->data['end_date']['year'].'-'.$this->request->data['end_date']['month'].'-'.$this->request->data['end_date']['day'];
//$continuity->start_date = $this->request->data['start_date'];
//$continuity->end_date = $this->request->data['end_date'];
$continuity->games = $this->request->data['games'];
debug($this->Continuities->newEntity($this->request->data)->toArray());
debug($continuity);
if ($result = $this->Continuities->save($continuity, ['associated'=>['Games']])) {
$this->Flash->success(__('The continuity has been updated.'));
return $this->redirect(['action' => 'view', $continuity->id]);
}
$this->Flash->error(__('Unable to update the continuity.'));
}
$games = $this->Continuities->Games->getGamesList();
$this->set(compact('continuity', 'games'));
}
最後edit.ctp格式:
<?= $this->Form->create($continuity) ?>
<fieldset>
<legend><?= __('Edit Continuity') ?></legend>
<?= $this->Form->input('start_date') ?>
<?= $this->Form->input('end_date') ?>
<?= $this->Form->input('games', ['multiple'=>true]) ?>
</fieldset>
<?= $this->Form->button(__('Submit')); ?>
<?= $this->Form->end() ?>
謝謝。
讓我在佈局中提及'games.ids'('tablename'._ids),沒有它,這是行不通的。非常感謝你 – 2016-06-30 12:08:07