Greetings to all. I don’t understand how to implement in yii2 correctly saving through a linked table. How many I didn’t try, it only worked out to implement it through beforesafe and save through foreach in turn. There must be a better way.
I wonder if I am describing the News model and how the controller function should work. If it is possible with an example ... In this way, information is added only to the News table.
Controller function code
public function actionCreate() { $news = new News(); $user = new User(); $category = Categorynews::find()->all(); $img = new Img(); $allnews = new Allnews(); // выполняет загрузку модели // if ($news->load(Yii::$app->request->post()) && $news->validate() & $user->validate() && $category->validate() && $img->validate()) { if ($news->load(Yii::$app->request->post())) { // Блок загрузки изображения $file = UploadedFile::getInstance($img, 'img'); //Get the uploaded file $fp = fopen($file->tempName, 'r'); //$content = fread($fp, filesize($file->tempName)); $content = file_get_contents($file->tempName); fclose($fp); $img->img = $content; //print_r($user->attributes); echo "<pre>"; print_r($news); // print_r($file); echo "</pre>"; $news->save(); // return $this->redirect(['index']); // return $this->redirect(['view', 'id' => $news->id]); } else { return $this->render('create', [ 'news' => $news, 'user' => $user, 'category' => $category, 'img' => $img, 'allnews' => $allnews, ]); } }
Model News
<?php namespace backend\models; use yii\db\ActiveRecord; class News extends ActiveRecord { public $current_date; //текущая дата public $queryCategory; //список категорий public $category_list = array(); public function rules() { return [ [['text','title','status','hot_news'], 'required','message' => 'Поле не должно быть пустым'], //являются обязательными и не должны быть пустыми [['created_date', 'updated_date'], 'safe'], [['category_list'], 'safe'] ]; } public function behaviors() { return [ [ 'class' => \voskobovich\behaviors\ManyToManyBehavior::className(), 'relations' => [ 'category' => 'category_list', 'user' => 'user_list', 'img' => 'img_list', ], ], ]; } //для определения текущей даты public function init(){ parent::init(); $this->current_date = date("Ymd H:i:s"); } public static function tableName() { return '{{%news}}'; } public function getAttributes($names = null, $except = []) { $attributes = parent::getAttributes($names = null, $except = []); return array_replace($attributes, [ 'category_list' => $this->category_list ]); } public function attributeLabels() { return [ 'id' => 'ID', 'title' => 'Title', 'text' => 'Text', 'status' => 'Status', 'hot_news' => 'Hot News', 'urlPruf' => 'Url Pruf', 'created_date' => 'Created Date', 'updated_date' => 'Updated Date', ]; } public function getImg() { return $this->hasMany(News::className(), ['id' => 'id_img']) ->viaTable('work_allnews', ['id_img' => 'id']); } public function getUser() { return $this->hasMany(News::className(), ['id' => 'id_user']) ->viaTable('work_allnews', ['id_user' => 'id']); } public function getCategoryNews() { return $this->hasMany(News::className(), ['id' => 'id_category']) ->viaTable('work_allnews', ['id_category' => 'id']); } public function getNews() { return $this->hasMany(News::className(), ['id' => 'id_news']) ->viaTable('work_allnews', ['id_news' => 'id']); } public function beforeSave($insert) { if(parent::beforeSave($insert)) { if($this->isNewRecord) { $this->created_date = $this->updated_date = $this->current_date; } else $this->updated_date = time(); return true; } else return false; } }
Similar models Pictures, Categories, Users
<?php namespace backend\models; use Yii; class Img extends \yii\db\ActiveRecord { public static function tableName() { return '{{%img}}'; } public function rules() { return [ [['img'], 'required'], [['img'], 'string'], ]; } public function attributeLabels() { return [ 'id' => 'id', 'img' => 'Img', ]; } public function getAllnews() { return $this->hasMany(Allnews::className(), ['id_img' => 'id']); } }