我有两个表users
和user_details
,user_details
我们之间有user_id
和user hasOne user_detail
字段user_detail belongs to user
,我有以下我的视图文件中的代码
echo $this->Form->create($user);
echo $this->Form->input('name');
echo $this->Form->input('email');
echo $this->Form->input('user_detail.first_name');
echo $this->Form->input('user_detail.last_name');
echo $this->Form->button(__('Submit'))
echo $this->Form->end()
我的UsersController
代码
public function add() {
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
$user = $this->Users->patchEntity($user, $this->request->data, [
'associated' => ['UserDetails']
]);
if ($this->Users->save($user)) {
$this->Flash->success(__('The user has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The user could not be saved. Please, try again.'));
}
}
$this->set(compact('user'));
$this->set('_serialize', ['user']);
}
如果我在补丁输入后的print_r($ user)比我得到的数据
App\Model\Entity\User Object
(
[name] => User1
[email] => user1@user2.com
[user_detail] => Array
(
[first_name] => user1
[last_name] => last naem
)
[[new]] => 1
[[accessible]] => Array
(
[*] => 1
)
[[dirty]] => Array
(
[name] => 1
[email] => 1
[user_detail] => 1
)
[[original]] => Array
(
)
[[virtual]] => Array
(
)
[[errors]] => Array
(
)
[[repository]] => Users
)
这是我的用户模型我删除了验证规则
<?php
namespace App\Model\Table;
use App\Model\Entity\User;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
/**
* Users Model
*
* @property \Cake\ORM\Association\HasMany $UserDetails
*/
class UsersTable extends Table
{
/**
* Initialize method
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize(array $config)
{
parent::initialize($config);
$this->table('users');
$this->displayField('id');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
$this->hasMany('UserDetails', [
'foreignKey' => 'user_id'
]);
}
}
?>
这是我删除验证规则的用户详细信息模型
<?php
namespace App\Model\Table;
use App\Model\Entity\UserDetail;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
/**
* UserDetails Model
*
* @property \Cake\ORM\Association\BelongsTo $Users
*/
class UserDetailsTable extends Table
{
/**
* Initialize method
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize(array $config)
{
parent::initialize($config);
$this->table('user_details');
$this->displayField('id');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
$this->belongsTo('Users', [
'foreignKey' => 'user_id',
'joinType' => 'INNER'
]);
}
public function buildRules(RulesChecker $rules)
{
return $rules;
}
}
但仅在user
表中的数据保存不在user_detail
表中,不知道问题是什么。