亲爱的,
我有两个与users表的ID字段相关的字段(solicitante和resolvedor),如何在index.ctp中显示这两个字段? 我在下面使用这个代码,但我不知道如何区分这两个字段,我只放了一个字段,因为当我把两个字段放在一起时,信息会自行重复
我的index.ctp
<?= $chamado->has('user') ? $this->Html->link($chamado->user->nome, ['controller' => 'Users', 'action' => 'view', $chamado->user->id]) : '' ?>
我的控制器
public function index()
{
$this->paginate = [
'contain' => ['Users']
];
$chamados = $this->paginate($this->Chamados);
$this->set(compact('chamados'));
$this->set('_serialize', ['chamados']);
}
我的模特
public function initialize(array $config)
{
parent::initialize($config);
$this->setTable('chamados');
$this->setDisplayField('id');
$this->setPrimaryKey('id');
$this->addBehavior('Timestamp');
$this->belongsTo('Users', [
'foreignKey' => 'solicitante',
'joinType' => 'INNER'
]);
}
跟随屏幕图像:
答案 0 :(得分:2)
你可以这样区分:
$this->belongsTo('Solicitantes', [
'className' => 'Users'
'foreignKey' => 'solicitante',
'joinType' => 'INNER'
]);
$this->belongsTo('Resolvedores', [
'className' => 'Users'
'foreignKey' => 'resolvedor',
'joinType' => 'INNER'
]);
并在您的视图中
<?= $chamado->has('solicitante') ? $this->Html->link($chamado->solicitante->nome, ['controller' => 'Users', 'action' => 'view', $chamado->solicitante->id]) : '' ?>
<?= $chamado->has('resolvedor') ? $this->Html->link($chamado->resolvedor->nome, ['controller' => 'Users', 'action' => 'view', $chamado->resolvedor->id]) : '' ?>
参见手册
https://book.cakephp.org/3.0/en/orm/associations.html#belongsto-associations