Yii2 — почему не создаются новые тэги?

Различные вопросы по установке и настройке фреймворка, конфигурции веб-сервера и IDE.
Ответить
Fin
Сообщения: 13
Зарегистрирован: 2017.06.18, 13:28

Yii2 — почему не создаются новые тэги?

Сообщение Fin »

Что нужно сделать, чтобы можно было создать и сохранить новый тэг на странице блога?

Код: Выделить всё

<?php

namespace common\models;

use Yii;
use common\models\Blog;
use yii\db\ActiveRecord;
/**
 * This is the model class for table "blog".
 *
 * @property integer $id
 * @property string $title
 * @property string $text
 * @property string $url
 * @property integer $status_id
 * @property integer $sort
 */
class Blog extends \yii\db\ActiveRecord {

   /* public $tags_array;*/
   public $tags_array;
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'blog';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['title', 'url'], 'required'],
            [['text'], 'string'],
            [['url'], 'unique'],
            [['status_id', 'sort'], 'integer'],
            [['sort'], 'integer','max'=>99, 'min'=>1],
            [['title', 'url'], 'string', 'max' => 150],
            [['tags_array'],'safe'],

        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'title' => 'Заголовок',
            'text' => 'Текст',
            'url' => 'ЧПУ',
            'status_id' => 'Статус',
            'sort' => 'Сортировка',
            'tags_array' => 'Тэги',
            'tagsAsString' => 'Тэги',
            'author.username'=>'Имя Автора',
            'author.email'=>'Почта Автора',



        ];
    }

    public static function getStatusList() {
        return ['off','on'];
    }
    public function getStatusName(){
       $list = self::getStatusList();
       return $list[$this->status_id];
    }

    public function getAuthor () {
      return $this->hasOne (User::className(),['id'=>'user_id']);
    
    }

     public function getBlogTag () {
      return $this->hasMany(BlogTag::className(),['blog_id'=>'id']);
    }

      public function getTags()
    {
      return $this->hasMany(Tag::className(),['id'=>'tag_id'])->via('blogTag');
    }

      public function getTagsAsString() 
    {  
       $arr = \yii\helpers\ArrayHelper::map($this->tags,'id','name');
       return implode (', ',$arr);
    }


      public function afterFind() 
    {  
       $this->tags_array = $this->tags;
    }

      public function afterSave ($insert, $changedAttributes) 
    {
      parent::afterSave($insert, $changedAttributes);

      $arr = \yii\helpers\ArrayHelper::map($this->tags,'id','id');
      foreach ($this->tags_array as $one) {
       if(!in_array($one,$arr)){
          $model = new BlogTag();
          $model->blog_id = $this->id;
          $model->tag_id = $one;
          $model->save();
      }
      if(isset($arr[$one])) {
         unset ($arr[$one]);
      }
      }
       BlogTag::deleteAll(['tag_id'=>$arr]);
  }
}  

таблица MySQl
http://upload.akusherstvo.ru/image1336410.jpg
Nex-Otaku
Сообщения: 831
Зарегистрирован: 2016.07.09, 21:07

Re: Yii2 — почему не создаются новые тэги?

Сообщение Nex-Otaku »

Возьмите готовое расширение: https://github.com/voskobovich/yii2-man ... y-behavior
Статья с объяснениями от автора: https://habrahabr.ru/post/244709/

Разберётесь, как подключить - избавите себя от кучи проблем.

Я использую его в работе, пока что всё хорошо. Разве что с кешем дружить не хочет )
Ответить