public function actionAdd($ingredientId) { // less queries here $postType = Posts::TYPE_USER_INGREDIENTS; $post = Posts::find()->where(['and', ['PostType' => $postType], ['UserID' => Yii::$app->user->getId()]])->one(); if (!$post) { $post = new Posts(); $post->PostType = $postType; $post->UserID = Yii::$app->user->getId(); $post->save(); } $ingredient = Tags::findOne($ingredientId); $post->link('tags', $ingredient); }