このコードを最適化またはリファクタリングできますか?これはタグ付けの最適なアプローチですか?
次のコードは、私の投稿モデルのコールバックです。タグをQuestionsTagsジョイナーテーブルの投稿に関連付けるレコードを作成します。必要に応じて、特定のタグがタグテーブルにまだ存在しない場合、関数はそのタグを作成し、そのIDを使用してQuestionsTagsテーブルに新しいレコードを作成します。
このアプローチの難しさは、QuestionsTagsテーブルが、存在する場合と存在しない場合があるタグテーブルのデータに依存することです。
この関数は、次のテーブルを想定しています。
tags(id, tagName),
posts(tags) // Comma delimited list
questionsTags(postId, tagId)
アイデアは、投稿とともに送信されたタグの区切られたリストをループし、各タグがタグテーブルにすでに存在するかどうかを確認することです。
タグが存在する場合:
- この投稿とこのタグのQuestionTagレコードがQuestionTagsテーブルにすでに存在するかどうかを確認してください。
- はいの場合、何もしません(関連付けはすでに存在します)
- いいえの場合、既存のタグのIDとpostIdを使用して新しいQuestionTagレコードを作成します
タグがまだ存在しない場合:
- タグテーブルに新しいタグを作成します
- そのIDを使用して、新しいQuestionsTagsレコードを作成します
コード
/**
* @hint Sets tags for a given question.
**/
private function setTags()
{
// Loop over the comma and space delmited list of tags
for (local.i = 1; local.i LTE ListLen(this.tags, ", "); local.i = (local.i + 1))
{
// Check if the tag already exists in the database
local.tag = model("tag").findOneByTagName(local.i);
// If the tag exists, look for an existing association between the tag and the question in the QuestionTag table
if (IsObject(local.tag))
{
local.questionTag = model("questionTag").findOneByPostIdAndTagId(values="#this.postId#,#local.tag.id#");
// If no assciatione exists, create a new QuestionTag record using the tagId and the postId
if (! IsObject(local.questionTag))
{
local.newQuestionTag = model("questionTag").new(postId = this.id, tagId = local.tag.id);
// Abort if the saving the new QuestionTag is unsuccesful
if (! local.newQuestionTag.save())
{
return false;
}
}
}
// If the tag does not exist create it
else
{
local.newTag = model("tag").new(tagName = local.i, userId = this.ownerUserId);
// Abort if the the new tag is not saved successfully
if (! local.newTag.save())
{
return false;
}
// Otherwise create a new association in the QuestionTags table using the id of the newly created tag and the postId
local.newQuestionTag = model("questionTag").new(postId = this.id, tagId = local.newTag.id);
// Abort if the new QuestionTag does not save correctly
if (! local.newQuestionTag.save())
{
return false;
}
}
}
}
参考:アプリケーションでCFWheelsを使用しています。これは、使用されるORM関数を説明しています。