이 코드를 최적화하거나 다시 적용 할 수 있습니까? 이것이 태그를 붙이는 최적의 접근 방법입니까?태그를 사용하는 것이 좋은 방법입니까?
다음 코드는 내 게시물 모델의 콜백입니다. 그것은 질문 태그 소목 장 테이블의 게시물과 태그를 연결하는 레코드를 생성합니다. 필요하다면 주어진 태그가 이미 tags 테이블에 존재하지 않으면 함수는 태그를 생성 한 다음 id를 사용하여 QuestionsTags 테이블에 새 레코드를 만듭니다.
이 접근법의 어려움은 QuestionTags 테이블이 태그 테이블의 데이터에 따라 달라 지거나 존재하지 않을 수 있다는 것입니다.
기능은 다음 표 가정
tags(id, tagName),
posts(tags) // Comma delimited list
questionsTags(postId, tagId)
아이디어는 포스트와 함께 제출 태그로 구분 된 목록을 통해 루프하고 각 태그가 이미 태그 테이블에 존재하는지 확인을
태그가있는 경우 : 이미이 게시물에 대한 QuestionTag 기록과 QuestionTags 테이블에이 태그가 있다면
- 점검보고 . 네, 아무 것도 설정하지 않으면
- 태그가 이미없는 경우 기존 태그의 ID와 postId
을 사용하여 새 QuestionTag 레코드를 생성,
- 새로운 QuestionsTags 레코드를 생성하기 위해 해당 ID를 사용하여 태그 테이블
- 의 새로운 태그를 생성
코드
/**
* @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;
}
}
}
}
는 참고 : 내가 사용하는 ORM 기능을 설명 내 응용 프로그램에 CFWheels을 사용하고 있습니다.
또한 for() 루프에서 local.i ++를 사용할 수 있습니다. –
아, 왜 함수에 인수를 전달하고 'arguments.tagList'등을 참조하는 대신 'this'범위를 만지고 있습니까? 'this'범위의 사용은 모범 사례 관점에서 다소 위태로운 것입니다. –
또한 목록의 태그 항목으로 'local.i'를 참조하는 것으로 혼란 스럽습니다. 실제 태그를 얻기 위해 listGetAt (thelist, i)를 할 필요가 없습니까? local.i는이 예제의 iterator입니다. –