我有一个实体卡和另一个练习组。
Card HAS MANY ExercisesGroup
// Fields
Card = name
ExercisesGroup = name, card_id
应用\模型\表\ CardsTable
$this->hasMany('ExercisesGroups', [
'foreignKey' => 'card_id'
]);
public function validationDefault(Validator $validator)
{
$validator
->add('id', 'valid', ['rule' => 'numeric'])
->allowEmpty('id', 'create')
->requirePresence('name', 'create')
->notEmpty('name')
return $validator;
}
应用\模型\表\ ExercisesGroupTable
$this->belongsTo('Cards', [
'foreignKey' => 'card_id'
]);
public function validationDefault(Validator $validator)
{
$validator
->add('id', 'valid', ['rule' => 'numeric'])
->allowEmpty('id', 'create')
->requirePresence('name', 'create')
->notEmpty('name')
->add('card_id', 'valid', ['rule' => 'numeric'])
->requirePresence('card_id', 'create')
->notEmpty('card_id');
return $validator;
}
public function buildRules(RulesChecker $rules)
{
$rules->add($rules->existsIn(['card_id'], 'Cards'));
return $rules;
}
我在保存卡片时需要保存ExercisesGroup,如下所示:
应用\控制器\控制器\ CardsController
$data = [
'name' => 'foo',
'exercises_groups' =>
[
['name' => 'exercise bar']
]
];
$card = $this->Cards->newEntity();
$card = $this->Cards->patchEntity($card, $data);
$this->Cards->save($card);
问题是,我收到此验证错误:
[
'exercises_groups' => [
(int) 0 => [
'card_id' => [
(int) 0 => 'This field is required'
]
]
]
]
我知道card_id是空的,但是我不能设置card_id,因为我还没有保存卡,所以我不知道它会是什么,我读了文档,我认为框架处理这个,什么可以我做错了吗?
线索 Cakephp正在识别关联,因为是验证ExercisesGroup数据。问题是:为什么他们要求外键自动填写。