Inserir registro em 2 tabelas
Estou tentando inserir registro em 2 tabelas (distributions e countries).
Estou usando CakePHP 3.5 e as tabelas do banco estão mais ou menos assim
- Distributions (id, name);
- Countries (id, distributions_id, name);
**DistributionsController:**
public function add() {
$topic = $this->Distributions->newEntity();
if($this->request->is('post')) {
$topic = $this->Distributions->patchEntity($topic, $this->request->data);
if($this->Distributions->save($topic, ['associated'=>'Countries'])) {
$this->request->data['Countries']['distributions_id'] = $this->Distributions->id;
$this->Flash->success(__('Cadastrado.'));
return $this->redirect(['action' => 'add']);
}
$this->Flash->error(__('Erro.'));
}
$this->set('topic', $topic);
}
**DistributionsTable:**
class DistributionsTable extends Table {
public function initialize(array $config) {
parent::initialize($config);
$this->table('distributions');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
$this->hasOne('Countries', [
'foreignKey' => 'distributions_id',
'joinType' => 'INNER'
]);
}
**Add.ctp (view add em distributions)**
<h1>Add Topic</h1>
<?php
echo $this->Form->create($topic);
echo $this->Form->input('name');
echo $this->Form->input('countries.name');
echo $this->Form->button(__('Salvar'));
echo $this->Form->end();
?>
**CountriesTable:**
class CountriesTable extends Table {
public function initialize(array $config) {
parent::initialize($config);
$this->table('countries');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
$this->belongsTo('Distributions');
}Discussão (0)
Carregando comentários...