我正在尝试使用CakePHP将一些数据保存到联合表中。这是我想要修复的应用程序的一部分 - 它是一个带有额外列的常规BelongsToMany关联:
模型 > 实体:
/* Durations */
class Duration extends Entity {
protected $_accessible = [
'duration' => true,
'cost' => true,
];
}
/* Commercials */
class Commercial extends Entity {
protected $_accessible = [
'info' => true,
'commercial_durations' => true,
];
}
/* CommercialDurations */
class CommercialDuration extends Entity {
protected $_accessible = [
'duration_id' => true,
'commercial_id' => true,
'quantity' => true,
'duration' => true,
'commercial' => true,
];
}
模型 > 表:
class DurationsTable extends Table {
public function initialize(array $config)
{
$this->table('durations');
$this->displayField('id');
$this->primaryKey('id');
$this->belongsToMany('Commercials', [
'through' => 'CommercialDurations',
]);
}
}
class CommercialsTable extends Table
{
public function initialize(array $config){
$this->table('commercials');
$this->displayField('id');
$this->primaryKey('id');
$this->belongsToMany('Durations', [
'through' => 'CommercialDurations'
]);
$this->hasMany('CommercialDurations', [
'foreignKey' => 'commercial_id'
]);
}
}
class CommercialDurationsTable extends Table {
public function initialize(array $config)
{
$this->table('commercial_durations');
$this->displayField('id');
$this->primaryKey('id');
$this->belongsTo('Durations', [
'foreignKey' => 'duration_id',
'joinType' => 'INNER'
]);
$this->belongsTo('Commercials', [
'foreignKey' => 'commercial_id',
'joinType' => 'INNER'
]);
}
}
现在,我创建了一个新的视图,希望人们能够选择一个持续时间,输入数量并将该值添加到数据库中。我正在使用以下代码:
<?php
echo $this->Form->create($commercial);
echo $this->Form->input('durations._duration', ['options' => $durations]);
echo $this->Form->input('durations._joinData.quantity');
echo $this->Form->submit(__('Next'), ['class' => 'button small right', 'escape' => false]);
echo $this->Form->end()
?>
这个表单的问题在于,持续时间选择器未显示来自“持续时间”表的“持续时间”字段,而是将该表中所有字段(每行一个)作为JSON显示。
<option value="0">{ "id": 1, "duration": "30 sec", "cost": 450 }</option>
当我提交表单后,无法将此信息保存到Commercials对象或CommercialDurations中。以下是我从 $this->request->data 对象获取的内容:
[
'durations' => [
'_duration' => '2',
'_joinData' => [
'quantity' => '2'
]
]
]
在我开始表格之前,debug((string)$commercial)的输出是:
/src/Template/Commercials/features.ctp (line 22)
'{
"id": 2,
"info": "AAAAAA ",
"created": "2015-04-16T21:48:48+0000",
"updated": null,
"durations": [],
}'
如何在表单上正确显示数据?如何检索和保存这些数据?谢谢!
$this->Form->create($commercial)
之前展示debug((string)$commercial)
的结果。 - José Lorenzo Rodríguez{ "id": 1, "duration": "30 sec", "cost": 450 }
这个是从哪里来的?你的实体中没有关于durations
的任何信息。 - José Lorenzo Rodríguez