H
H
happ2016-08-06 17:16:17
Yii
happ, 2016-08-06 17:16:17

How to generate a request to add a post and tags in Yii2?

I saved the post, got the post id, I form a request to add tags to the post using the Tags model, this model will contact the PostTag model responsible for saving tags and posts. Saving will be done using active record.
2 questions:
1. Is the logic correct (If not, how is it correct)?
2. The Tags model has a tags public property, and using load it is not possible to load data into the model, what could be the reason for this?
if($model->load(Yii::$app->request->post()) && $model->upload($imgFile) && $model->validate() && $model->add()) {
//adding tags
//post id for which there will be tags
$postTagId = Yii::$app->db->getLastInsertID();
var_dump(Yii::$app->request->post());
if($tagsModel->load(Yii::$app->request->post()) && $tagsModel->validate() && $tagsModel->save()) {
}
}
----
Model Tags
class Tags extends Model {
public $tags = array();
/*
* Returns an array, column index is id.
* */
public static function getTagsAsIndexArr() {
return Tag::find()->select(['title', 'id'])->indexBy('id')->column();
}
public function save() {
var_dump($this);
}
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Timofeev, 2016-08-06
@happ

You need: a post table with id and a tag table with id and name + a post_tag table with id, post_id, tag_id that connects them
Create a public tags variable in the Post model, and then iterate over the tags in the afterSave method of the post model:
save the new ones and link them, unbind the old ones .
$this->id will be available here. it will not be necessary to do this horror -

$postTagId = Yii::$app->db->getLastInsertID();

If, apart from posts, tags are still needed somewhere, you can make the post_tag table more universal by adding the modul field and writing the module name there or $this->className().
You can go further and make behavior out of this, conveniently connecting to any model.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question