A
A
Allanian2016-09-04 11:15:43
This
Allanian, 2016-09-04 11:15:43

How to implement persistence in Yii2 Many to many?

Welcome all.
I don’t understand a little how to correctly implement saving through a linked table in yii2 No matter how
much I tried, it turned out only to implement it through beforesafe and through foreach to save in turn. There must be a better way.
Interested in whether I describe the News model correctly and how the controller function should work

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, 'image');   //Get the uploaded file
            //  $fp = fopen($file->tempName, 'r');
            //$content = fread($fp, filesize($file->tempName));
            //   $content = file_get_contents($file->tempName);
            //    fclose($fp);
            //     $img->image = $content;
            
            $news->save();

        } else {
            return $this->render('create', [
                'news' => $news,
                'user' => $user,
                'category' => $category,
                'img' => $img,
                'allnews' => $allnews,
            ]);
        }
    }

There are 5 tables
Authors, Pictures, Tags, News, News Pictures Tags Authors (in it ID of all tables)
In all models, the code is identical to the following
<?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']);
    }
}

Model News
<?php

namespace backend\models;

use yii\db\ActiveRecord;

class News extends ActiveRecord
{
    public $current_date;    //текущая дата
    public $queryCategory;   //список категорий
    
    public function rules()
    {
        return [
            [['text','title','status','hot_news'], 'required','message' => 'Поле не должно быть пустым'],    //являются обязательными и не должны быть пустыми
            [['created_date', 'updated_date'], 'safe'],
            [['category_list'], 'safe']
        ];
    }
    
    //для определения текущей даты
    public function init(){
        parent::init();
        $this->current_date = date("Y-m-d H:i:s");
    }
    
    
    public static function tableName()
    {
        return '{{%news}}';
    }


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

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
E
enchikiben, 2016-09-04
@EnChikiben

i used this https://github.com/voskobovich/yii2-many-to-many-b...

Similar questions

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question