可以做这样的事吗?
模型:
acc => x => acc.concat([f(x)])
上传模型:
class Model1 extends ActiveRecord {
public $contentUploadedFile;
...
public function extract() {
... (assign values from uploaded file content to Model attributes, e.g:)
$this->datum = $contentUploadedFile[1];
...
}
}
上传控制器:
class UploadModel extends Model {
public $uploadedFiles;
public function rules() {
return [
[['uploadedFiles'], 'file', 'extensions' => 'txt', 'checkExtensionByMimeType' => false, 'skipOnEmpty' => true, 'maxFiles' => 2],
];
}
}
但它不起作用(未定义的变量contentUploadedFile)。也许我的逻辑是完全错误的。总而言之,是否有可能将值传递给另一个类似的东西?或者这是完全错误的逻辑?如果在Yii2中有一个内置功能可以处理多个创建的模型,但不使用表单,并且仍然通过适当的验证,那将是很好的。有这样的事吗? 感谢。
答案 0 :(得分:0)
以这种方式尝试第一步
class UploadController extends Controller {
...
public function actionUpload() {
$model = new UploadModel;
if (Yii::$app->request->isPost && $model->validate()) {
$files = UploadedFile::getInstances($model, 'uploadedFiles');
foreach ($files as $file) {
$t = new Model1;
$t->contentUploadedFile = file($file->tempName);
// first try local assigment when all work transfer the logic in the model extract() function
$t->dbfield1 = $t->contentUploadedFile->field1
$t->dbfield2 = $t->contentUploadedFile->field2
// $t->extract();
//
if ($t->validate()) {
$t->save();
} else {
// validation failed: $errors is an array containing error messages
$errors = $t->errors;
var_dump($errors);
}
if
}
}
return $this->render('upload', [
'model' => $model,
]);
}
}
对于模型,使用$ this来引用属性
class Model1 extends ActiveRecord {
public $contentUploadedFile;
...
public function extract() {
... (assign values from uploaded file content to Model attributes, e.g:)
$this->datum = $this->$contentUploadedFile[1];
...
}
}