Here is the code: I have 3 objects, and 3 model. The note, have many tags, and every tags must have one note. So, I have a note_tag_list to store the tags and notes relationship.
The program is create a note, with some tags.
First, I create a note object, and put it into the model. And I get back the object from the model. And I detect whether the tag is exist, just don't create, otherwise, create it. Then, I read back the tag object from the db. And use all the tags and note to create new note_tag_list object, and put this object to the model. Then, it finished.
But I think it seems very complex for my flow. Any ways to do it more elegant? Thank you.
//load all the object
$this->load->library('obj_note');
$this->load->library('obj_tag');
$this->load->library('obj_note_tag_list');
//load all the model
$this->load->model('note_model');
$this->load->model('tag_model');
$this->load->model('note_tag_list_model');
//create a note object
$aNewUserNote =new obj_note();
//set the object information
$user_id =get_current_user_id();
$title =$this->input->post('ui_title_input');
$content_url =$this->input->post('ui_url_input');
$content =$this->input->post('ui_textarea');
$right =RIGHT_NOTE_PUBLIC;
$status =STATUS_NOTE_ACTIVE;
$aNewUserNote->set_user_id($user_id);
$aNewUserNote->set_title($title);
$aNewUserNote->set_content_url($content_url);
$aNewUserNote->set_content($content);
$aNewUserNote->set_right($right);
$aNewUserNote->set_status($status);
$aNewlyCreateNoteId = 0;
if(!$this->note_model->create_note_by_note($aNewUserNote, $aNewlyCreateNoteId))
{
//create success
return;
}
//get back the object from the model
$aNewlyCreateObj = $this->note_model->read_note_by_note_id($aNewlyCreateNoteId);
$aTagNameString = $this->input->post('ui_tag');
$tagsStringArray = $this->convert_tags_string_to_lower_case_string_array($aTagNameString);
$aTagArray = array();
$createNewTagIsSuccess = FALSE;
//Create New Tag
for($i = 0; $i < count($tagsStringArray); $i++)
{
$aTagObj = $this->tag_model->read_tag_by_tag_name($tagsStringArray[$i]);
if($aTagObj == NULL)
{
$aNewTag =new obj_tag();
$aNewTag->set_create_user_id($user_id);
$aNewTag->set_tag_name($tagsStringArray[$i]);
if(!$this->tag_model->create_tag_by_tag($aNewTag)) //create tag fail
{
$createNewTagIsSuccess = FALSE;
}
}
}
//Read all the tag
for($j = 0; $j < count($tagsStringArray); $j++)
{
$aTagObj = $this->tag_model->read_tag_by_tag_name($tagsStringArray[$j]);
$aTagArray[count($aTagArray)] = $aTagObj;
}
//Make the note, and tag have relationship
for($k = 0; $k < count($aTagArray); $k++)
{
$theTagObj = $aTagArray[$k];
$aNoteTagList = new obj_note_tag_list();
$aNoteTagList->set_note_id($aNewlyCreateObj[0]->get_id());
$aNoteTagList->set_tag_id($theTagObj[0]->get_id());
$this->note_tag_list_model->create_note_tag_list_by_note_tag_list($aNoteTagList);
}
for
where you should useforeach
), but that's all I'm doing. – adlawson Aug 22 '11 at 12:21