Я пытаюсь сохранить некоторые данные в объединенную таблицу, используя 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": [],
}'
Как правильно отобразить данные на форме? Как я могу получить и сохранить эти данные?
Спасибо!!
debug((string)$commercial)
перед вызовом$this->Form->create($commercial)
- person José Lorenzo Rodríguez   schedule 22.04.2015{ "id": 1, "duration": "30 sec", "cost": 450 }
? В вашей сущности нет ничего оdurations
- person José Lorenzo Rodríguez   schedule 23.04.2015