yii2将变量传递到另一个模型

j0pj023g  于 2022-11-09  发布在  其他
关注(0)|答案(1)|浏览(168)

有可能做这样事情吗?
型号:

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],
        ];
    }
}

上传控制器:

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);

                $t->extract();
                $t->save();
            }
        }

        return $this->render('upload', [
                    'model' => $model,
        ]);
    }
}

但是它不工作(未定义的变量contentUploadedFile)。也许我的逻辑是完全错误的。总而言之,有没有可能把值传递给另一个类似的模型呢?或者它是完全错误的逻辑?如果在Yii2中有一个内置的功能可以处理多个创建的模型,但是不使用表单,并且仍然有适当的验证,那就太好了。有这样的功能吗?谢谢。

f2uvfpb9

f2uvfpb91#

尝试第一步

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];
        ...
   }
}

相关问题