cakephp - beforeSave 方法在 cakephp3 中不起作用
问题描述
我有数据要先修改,然后再将其保存到我的数据库中,因此我研究了 beforeSave 方法。
我有一个用户的图片输入,我想在成功验证后将其路径保存在我的数据库中,这是我当前的代码:
src/model/table/UsersTable.php
use Cake\ORM\Entity;
use Cake\Event\Event;
use ArrayObject;
use Cake\Validation\Validator;
public function validationDefault(Validator $validator)
{
$validator
->allowEmptyFile('image_location')
->add('image_location',
[
'mimeType' => [
'rule' => array('mimeType', array( 'image/png', 'image/jpg', 'image/jpeg')),
'message' => 'Please upload images only (png, jpg).'
],
'fileSize' => [
'rule' => array('fileSize', '<=', '10MB'),
'message' => 'Image must be less than 10MB.'
],
]);
return $validator;
}
public function beforeSave($event, $entity, $options)
{
if ($entity->image_location['name']) {
$tmp = $entity->image_location['tmp_name'];
$hash = rand();
$date = data("Ymd");
$image = $dage.$hash;
$target = WWW_ROOT.'img'.DS.'uploads'.DS;
$target = $target.basename($image);
$image_location = "uploads/".$image;
$entity->image_location = $image_location;
move_uploaded_file($tmp, $target);
}
}
唯一有效的部分是验证部分,但是在成功验证图像文件后, beforeSave 方法不起作用。
我当前的代码有什么错误,或者如何在 cakephp3 中使用 beforeSave 方法。
非常感谢!
编辑
我什至试过这条线:
public function beforeSave($event, $entity, $options)
{
debug($entity);
if ($entity->image_location['name']) {
$tmp = $entity->image_location['tmp_name'];
$hash = rand();
$date = data("Ymd");
$image = $dage.$hash;
$target = WWW_ROOT.'img'.DS.'uploads'.DS;
$target = $target.basename($image);
$image_location = "uploads/".$image;
$entity->image_location = $image_location;
move_uploaded_file($tmp, $target);
}
}
检查 beforeSave 方法正在接收的实体,但它不输出任何内容。
解决方案
推荐阅读
- python-3.x - 如何使用 Python 在 Google Drive 上的文件夹中搜索文件
- jmeter - 如何使用 Jmeter 进行 UI 性能测试?
- javascript - 为什么承诺同时有效?
- r - 如何从字符串中提取带有“e”的数字部分
- python-3.x - 使用 Kivy 模块的 Py 程序
- apache-cayenne - 继承 - 数据库关系
- javascript - react-slide-toggle 移除 onExpanded 时隐藏的溢出
- kubernetes - 在现有 Azure AKS 群集上启用群集自动缩放程序
- python - 未绘制熊猫数据
- javascript - 这是来自文件或浏览器内存的流式传输吗?