M
M
Maila2017-07-08 23:01:59
Yii
Maila, 2017-07-08 23:01:59

Yii2 advanced - why tags are not saved?

There are only 2 saved tags in the database, and 3 are not created by 'update' in any way ( 7ebb02a65c624b5a9288fb39fcd4ecf3.jpg
file Blog.php

<?php

namespace common\models;

use Yii;
use common\models\Blog;

/**
 * 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;
    /**
     * @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' => 'Тэги',

        ];
    }

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

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
M
Maxim Timofeev, 2017-07-09
@webinar

See logs, debug variables. Perhaps afterSave does not work for you at all, since the blog itself does not pass validation. Tons of options.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question