0

我有一个关于 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,
];
4

2 回答 2

0

我觉得每件事看起来都不错。可能是您在表中的字段的默认值为空。例如:

If 'rating_value' field in your table has default value null,
make that default full to none first.

如果验证失败,则不会让您保存任何内容而不是保存空值。如果这仍然对您不起作用,请参阅:

debug($this->request->data);

如果数据来自您的视图(表单)正确,请查看那里。另一个重要的事情是您可以使用不同的验证集进行关联。(见这里

于 2017-01-05T14:34:23.150 回答
0

如果您正在设置 rating_value ,那么它将尝试保存并使用所有验证规则进行验证。

如果 rating_value 像这样为空,您可以删除关联的数据

$dataToSave = $this->request->data;
if(empty($dataToSave['rating']['rating_value'])){
    unset($dataToSave['rating']);
}
$article = $this->Articles->patchEntity($article, $dataToSave, [
    'associated' => [
        'Ratings',
    ]
]);
于 2017-01-05T15:52:47.323 回答