所以我有一个Users表和一个Security Questions表。我能够创建一个具有相关安全问题的用户,但是当我查看配置文件时,我无法正确显示displayField。
这是UsersTable.php的代码
public function initialize(array $config)
{
parent::initialize($config);
$this->table('users');
$this->displayField('email');
$this->primaryKey('id');
$this->hasOne('SecurityQuestions',
[ 'foreignKey' => 'security_question_id']);
$this->addBehavior('Timestamp');
}
以下是SecurityQuestionsTable.php的代码
public function initialize(array $config)
{
parent::initialize($config);
$this->table('security_questions');
$this->displayField('question');
$this->primaryKey('security_question_id');
$this->hasMany('Users', ['foreignKey'=>'security_question_id', 'bindingKey'=>'security_question_id']);
$this->belongsTo('SecurityQuestions', [
'foreignKey' => 'security_question_id',
'joinType' => 'INNER'
]);
}
这是我的UsersController.php视图方法:
public function view($id = null)
{
$user = $this->Users->get($id, [
'contain' => []
]);
$this->set('user', $user);
$this->set('_serialize', ['user']);
}
最后但并非最不重要的是,视图代码
<h3><?= h($user->id) ?></h3>
<table class="vertical-table">
<tr>
<th><?= __('Email') ?></th>
<td><?= h($user->email) ?></td>
</tr>
<tr>
<th><?= __('Password') ?></th>
<td><?= h($user->password) ?></td>
</tr>
<tr>
<th><?= __('First Name') ?></th>
<td><?= h($user->first_name) ?></td>
</tr>
<tr>
<th><?= __('Last Name') ?></th>
<td><?= h($user->last_name) ?></td>
</tr>
<tr>
<th><?= __('Id') ?></th>
<td><?= $this->Number->format($user->id) ?></td>
</tr>
<tr>
<th><?= __('Created') ?></th>
<td><?= h($user->created) ?></td>
</tr>
<tr>
<th><?= __('Expiration') ?></th>
<td><?= h($user->expiration) ?></td>
</tr>
<tr>
<th><?= __('User Status') ?></th>
<td><?= h($user->user_status) ?></td>
</tr>
<tr>
<th><?= __('Security Question') ?></th>
<td><?= h($user->security_question_id) ?></td>
</tr>
<tr>
<th><?= __('Security Question Answer') ?></th>
<td><?= h($user->security_question_answer) ?></td>
</tr>
</table>
我是CakePHP的新手。
答案 0 :(得分:0)
你需要改变一些小事。
在您的UsersTable中:
$user = $this->Users->get($id, [
'contain' => []
]);
需要
$user = $this->Users->get($id, [
'contain' => ['SecurityQuestions']
]);
在您的视图文件中:
<tr>
<th><?= __('Security Question') ?></th>
<td><?= h($user->security_question_id) ?></td>
</tr>
需要
<tr>
<th><?= __('Security Question') ?></th>
<td><?= h($user->security_question->question) ?></td>
</tr>
显示字段主要用于创建下拉列表,以及一些构建脚手架视图的插件(如crud-view)。