Answer the question
In order to leave comments, you need to log in
How can I connect two models in yii2?
I have two models, one for uploading a file to the server, and the other for adding an entry to the database with the name of the given file:
Model Info:
class Info extends ActiveRecord
{
public static function tableName()
{
return '{{info}}';
}
public function rules() {
return [
,
[['title', 'preview', 'description_seo'], 'filter', 'filter' => 'strip_tags'],
[['title', 'preview', 'description_seo'], 'trim'],
[['title', 'preview', 'description_seo'], 'required'],
[['img_preview', 'img_full'], 'file', 'skipOnEmpty' => false, 'extensions' => 'jpg, jpeg'],
['description', 'safe'],
];
}
public function attributeLabels()
{
return [
'title' => 'Заголовок',
'preview' => 'Превью',
'description' => 'Описание новости',
'img_preview' => 'Фотография (Превью)',
'img_full' => 'Фотография (Основная)',
'description_seo' => 'Description (SEO)',
];
}
}
class InfoUpload extends Model
{
public $img_preview;
public $img_full;
public function upload() {
// Создание директории
$folderName = $this->generateUniqFileName("web/info");
FileHelper::createDirectory( Yii::getAlias("@frontend/web/img/info/$folderName") );
// Создание файла
$imgPreviewName = $folderName . '/' . $this->generateUniqFileName("web/info/$folderName") . '.' . $this->img_preview->extension;
$this->img_preview->saveAs( Yii::getAlias("@frontend/web/img/info/$imgPreviewName") );
// Создание Файла
$imgFullName = $folderName . '/' . $this->generateUniqFileName("web/info/$folderName") . '.' . $this->img_full->extension;
$this->img_full->saveAs( Yii::getAlias("@frontend/web/img/info/$imgFullName") );
}
public function generateUniqFileName($path) {
$name = bin2hex(random_bytes(8));
if ( file_exists( Yii::getAlias("@frontend/$path/$name") ) ) return $this->generateUniqFileName();
else return $name;
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question