Answer the question
In order to leave comments, you need to log in
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 (
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
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 questionAsk a Question
731 491 924 answers to any question