Answer the question
In order to leave comments, you need to log in
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
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();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question