@Maila

Yii2 advanced — почему не сохраняются тэги?

В базе данных есть только 2 сохранённых тэга, а 3 не создаётся при 'update' никак( 7ebb02a65c624b5a9288fb39fcd4ecf3.jpg
файл 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();
      }
    }
  }
}
  • Вопрос задан
  • 280 просмотров
Пригласить эксперта
Ответы на вопрос 1
webinar
@webinar Куратор тега Yii
Учим yii: https://youtu.be/-WRMlGHLgRg
Смотрите логи, дебажте переменные. Возможно у Вас банально afterSave вообще не срабатываете, так как сам blog не проходи валидацию. Масса вариантов.
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы