$list = new Model_List(); $list->title = Input::post('title'); $list->content = Input::post('content'); $list->tags = new Model_Tag(); $list->tags->type = ? $list->tags->name = ? $list->save();
Jelmer Schreuder wrote on Saturday 21st of May 2011:$list->tags is an array, you can add new objects to that array.
$list->tags = array( new Model_Tag(array( 'type' => 'Genre', 'name' => 'Action', )), new Model_Tag(array( 'type' => 'Genre', 'name' => 'Adventure', )), );
Jelmer Schreuder wrote on Saturday 21st of May 2011:Just try
Fuel\Core\Database_Exception [ 1062 ]: Duplicate entry 'Action' for key 'name' [ INSERT INTO `tags` (`type`, `name`) VALUES ('Genre', 'Action') ]
Jelmer Schreuder wrote on Saturday 21st of May 2011:That really has nothing to do with the Orm, that's because you made the column unique and entered a duplicate.
$tag = Model_Tag::query()->where('name', $name)->get_one(); if (empty($tag)) { $tag = new Model_Tag(); $tag->name = $name; }
$_tags = explode(', ', Input::post('genre')); $tags = array(); foreach($_tags as $tag) { $query = Model_Tag::find()->where('name', $tag); if ($query->count() > 0) { $query->get_one(); //if the tag exists I need to access the list_id insert the tag id and list_id to 'list_tags' table } else { $tags[] = new Model_Tag(array( 'type' => 'Genre', 'name' => $tag, )); } } if ( ! empty($tags)) { $list->tags = $tags; }
Dregond Rahl wrote on Sunday 22nd of May 2011:The code below works just fine, for new tags it inserts the values to the 'tags' table and the 'list_tags' table. The problem is when a tag already exists, then it won't be able to insert it to the database. Yes I can retrieve the 'tag_id'. But I how would I get and insert the 'list_id' and insert the 'tag_id' I retrieved into the 'list_tags' which is the table through for connecting the lists table to the tags table.
$_tags = explode(', ', Input::post('genre')); $tags = array(); foreach($_tags as $tag) { $query = Model_Tag::find()->where('name', $tag); if ($query->count() > 0) { $query->get_one(); //if the tag exists I need to access the list_id insert the tag id and list_id to 'list_tags' table } else { $tags[] = new Model_Tag(array( 'type' => 'Genre', 'name' => $tag, )); } } if ( ! empty($tags)) { $list->tags = $tags; }
Controller : http://scrp.at/5f4a5c56c499188fe160a4d415cb8593fd21057c
Jelmer Schreuder wrote on Sunday 22nd of May 2011:@Dregond
Just retrieve the existing Tag model instance like I showed before and add it to the $list->tags array, it'll be automaticly inserted into the table. @Huglester
Your suggestion isn't actually good practice, though if I remember correctly there was a good reason in your setup.
It looks like you're new here. If you want to get involved, click one of these buttons!