我有一个关于 CakePHP 的小项目。它有一个名为articles的表,以及category、tags、images等5个Fields表。关联大多是HasOne,关联表有多个列。在文章表上保存数据时,一切看起来都很好,但在某些关联上,例如:文章 -> 评级,如果我没有填写评级表的某些字段,则将其保存为空:
+----+------------+--------------+
| id | article_id | rating_value |
+----+------------+--------------+
| 1 | 36 | 3 |
| 2 | 56 | 5454.56 |
| 3 | 57 | 4 |
| 5 | 51 | NULL |
+----+------------+--------------+
如果我添加一些验证,那么我无法保存文章,因为它需要验证。我想要的只是,如果 rating_value 为空,则不能将其创建为 null(实体被拒绝),并且必须保存文章。删除文章按预期工作,所有相关实体都被删除。
我尝试在 Model.beforeMarshall 上更改 $data 但该类在 Tables Articles 和 Ratings 中都是私有的(我认为关联可能是问题所在)。
一些代码(控制器添加):
public function add()
{
$article = $this->Articles->newEntity();
if ($this->request->is('post')) {
$article = $this->Articles->patchEntity($article, $this->request->data, [
'associated' => [
'Ratings',
]
]);
if ($this->Articles->save($article)) {
$this->Flash->success(__('Saved.'));
return $this->redirect(['action' => 'index']);
}
}
$this->set('article', $article);
}
因此,我删除了每个关联模型的所有验证。
// Articles Table
$this->hasOne('Ratings', [
'className' => 'Ratings',
'dependent' => true,
]);
// Ratings Table
$this->belongsTo('Articles', [
'foreignKey' => 'article_id',
'joinType' => 'INNER'
]);
// Rating.php Entity
protected $_accessible = [
'*' => true,
'id' => false
];
// Article.php Entity
protected $_accessible = [
'*' => true,
];