我想得到这个结果:Click Me (获取转到另一个关联表的链接)
我正在按照 cakephp 的官方教程将表链接在一起,但是 但它不起作用。
我的数据库是这样的:
表格城市:
| id (int 4) PK | nombreCiudad (varchar 60)|
表格组合:
| idComplejo(int 11)PK |名称 (varchar 25)| ciudad_id (int 4) FK | ciudad_id (int 4)
当我想显示另一个关联模型的名称 (ciudad nombreCiudad) 时,我的 complejo 表中的完整 ciudad 列为空。我想显示 Ciudad 的名称,而不是 ID。 在这里您可以看到空列:Click Me 2
当我想显示结果时,在index.ctp中 "$complejo->has('ciudad')" 返回 false:
<table cellpadding="0" cellspacing="0">
<thead>
<tr>
<th><?= $this->Paginator->sort('idComplejo') ?></th>
<th><?= $this->Paginator->sort('nombre') ?></th>
<th><?= $this->Paginator->sort('ciudad_id') ?></th>
<th class="actions"><?= __('Actions') ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($complejos as $complejo): ?>
<tr>
<td><?= $this->Number->format($complejo->idComplejo) ?></td>
<td><?= h($complejo->nombre) ?></td>
<td><?= $complejo->has('ciudad') ? $this->Html->link($complejo->ciudad->nombreCiudad, ['controller' => 'Ciudades', 'action' => 'view', $complejo->ciudad->id]) : '' ?></td>
<td class="actions">
<?= $this->Html->link(__('View'), ['action' => 'view', $complejo->idComplejo]) ?>
<?= $this->Html->link(__('Edit'), ['action' => 'edit', $complejo->idComplejo]) ?>
<?= $this->Form->postLink(__('Delete'), ['action' => 'delete', $complejo->idComplejo], ['confirm' => __('Are you sure you want to delete # {0}?', $complejo->idComplejo)]) ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
在这里你可以看到ciudades和complejos之间的关系 ComplejosTable.php
public function initialize(array $config)
{
parent::initialize($config);
$this->table('complejos');
$this->displayField('idComplejo');
$this->displayField('nombre');
$this->belongsTo('Ciudades', [
'foreignKey' => 'ciudad_id',
'joinType' => 'INNER'
]);
}
public function buildRules(RulesChecker $rules)
{
$rules->add($rules->existsIn(['ciudad_id'], 'Ciudades'));
return $rules;
}
这是CiudadesTable.php
...
public function initialize(array $config)
{
parent::initialize($config);
$this->table('ciudades');
$this->displayField('nombreCiudad');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
$this->hasMany('Complejos', [
'foreignKey' => 'ciudad_id'
]);
}
最后,在我的 ComplejosController 中,我有:
public function index()
{
$this->paginate = [
'contain' => ['Ciudades']
];
$this->set('complejos', $this->paginate());
$this->set('_serialize', ['complejos']);
}
我可以做什么来解决我的问题?感谢您的帮助。
最佳答案
只需将ciudad更改为ciudade
<td><?= $complejo->has('ciudade') ? $this->Html->link($complejo->ciudade->nombreCiudad, ['controller' => 'Ciudades', 'action' => 'view', $complejo->ciudade->id]) : '' ?></td>
对于 Cakephp 来说,Ciudades 的单数是 Ciudade 而不是 Ciudad
关于php - 在 Cakephp 中将两个模型之间的表链接在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37646523/