【发布时间】:2017-01-05 13:43:27
【问题描述】:
我有一个关于 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,
];
【问题讨论】:
-
"我尝试在 Model.beforeMarshall 上更改 $data"... 显示您尝试过的内容,因为这是要走的路(至少一种方式)。还要详细说明“类是私有的”,这句话对我来说真的没有意义。
-
在 Articles.beforeMarshall
var_dump($data)上显示object(ArrayObject)[272] private 'storage' => ...我无法修改数据,而 Ratings.beforeMarshall 相同object(ArrayObject)[231] private 'storage' => ... -
这就是转储array object 的样子,它的内部是私有的,但是可以不受限制地访问数据,只需像编辑任何其他数组一样编辑
$data。 book.cakephp.org/3.0/en/orm/… -
你一直都是对的。我试图编辑 $data->storage... 或 $data['storage']... 之类的数据,但只有 $data['field'] 有效。我认为这是一个比在控制器上做更好的解决方案。
标签: php cakephp cakephp-3.3