[英]Linking tables together between two models in Cakephp
我想得到这个结果: 单击我 (获取指向另一个关联表的链接)
我正在遵循cakephp的官方教程将表链接在一起,但是它不起作用。
我的数据库是这样的:
桌椅:
| id(int 4)PK | nombreCiudad(varchar 60)|
表complejos:
| idComplejo(int 11)PK | nombre(varchar 25)| ciudad_id(int 4)FK |
当我想显示另一个关联模型(ciudad nombreCiudad)的名称时,我的complejo表中的完整ciudad列为空。 我要显示名称,而不是Ciudad的ID。 在这里您可以看到空白列: 单击我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']);
}
我该怎么做才能解决我的问题? 感谢您的帮助。
你的:
<th><?= $this->Paginator->sort('user_id') ?></th>
似乎正在引用user_id,这在您的CiudadesTable中不可用。 您可能需要将其更改为
<th><?= $this->Paginator->sort('ciudad_id') ?></th>
只需将ciudad更改为ciudade
<td><?= $complejo->has('ciudade') ? $this->Html->link($complejo->ciudade->nombreCiudad, ['controller' => 'Ciudades', 'action' => 'view', $complejo->ciudade->id]) : '' ?></td>
对于CakePHP的奇异Ciudades的是Ciudade不城
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.