删除行并在数据透视表laravel中插入行

时间:2014-10-20 22:11:30

标签: php html laravel eloquent blade

嗨我正在尝试在发生以下情况时更新我的​​tagtask表(数据透视表):

因此,例如,我们已经有一个任务,其中包含3个标签,例如营销,开发,会计。现在我们要编辑该任务并删除这3个标签并添加1个名为cooking的标签。

所以我已经想到的是从tagtask表中删除这3个标签并添加标签'cooking' 在tagtask表中。此外,我不会从标签表中删除标签,因为可能有任务使用营销或开发或会计标签。

不幸的是,关于第一部分我的想法是我无法实现的。为了向您展示我尝试过的内容,我将首先向您展示我的观点代码:

{{Form::model($task,array('route'=>array('user.tasks.update', $task->id), 'method'=>'put'))}}
    <ul>
        <li>
                {{Form::label('tag', 'tags')}}
                <input type="text" name="tag_name" class="form-control" value='@foreach($task->tagtask as $tt){{$tt->tag['tag_name']}} @endforeach'>
        </li>
        <li>
                {{Form::submit('Edit Task',  array('class' => 'btn btn-default'))}}
        </li>
    </ul>
{{Form::close()}}

这是我的TaskController.php,包含以下代码:

<?php 
public function update($id)
    {
        $task = Task::findOrFail($id);
        $str = Input::get('tag_name');
        //Split string by a regular expression
        $arrayTags = preg_split('/[, ;]/', $str);

        $tt_current = Tagtask::where('id_task', $id)->get();
        $tags_raw = Tag::all();
        $tags =  array();

        foreach($tags_raw as $tag) 
        {   
            $tags[$tag->tag_name] = $tag->id;
        }

        foreach($arrayTags as $tag) 
        {

            if(!isset($tags[$tag])){
                //The tag doesn't exist. So we store a tag and get a new ID.
                        $id_tag=DB::table('tags')->insertGetId(
                                array('tag_name' => $tag)
                                );

                        $data_TagTask= array(
                                'id_task' => $id,
                                'id_tag' => $id_tag
                                );

                        $id_tagtask=DB::table('tagtasks')->insertGetId($data_TagTask);
                        $row= DB::table('tagtasks')->where('id', $id_tagtask)->first();

            } else {
                //The tag does exist
                foreach($tt_current as $tt) 
                {   //the following below is maybe wrong..
                    if ($tt->id_tag ==  $tags[$tag] && $tt->id_task == $row->id_task ) {
                        Tagtask::destroy($row->id_task);
                    }
                    //$tags[$tag->tag_name] = $tag->id;
                    //if(isset($tags_current[$id_task]))
                    //unset($tags_current[$id_task]);
                }
            }   
        }
        //print_r($tags)
        //die();
        return Redirect::route('user.tasks.index');
    }

所以我用该代码实现的是,我可以在视图中删除3个标签(如前所述)并添加新标签进行更新。然后将新标记存储在tagtask表和标记表中,但问题是旧的3标记仍在tagtask表中。虽然他们应该被删除..有人可以帮助我吗?很高兴我在等你的回答。无论如何,谢谢你的回答。

2 个答案:

答案 0 :(得分:1)

您应该使用sync。也许我错过了一些东西,但代码应该是这样的:

public function update($id)
{
    $task = Task::findOrFail($id);
    $str = Input::get('tag_name');
    //Split string by a regular expression
    $arrayTags = preg_split('/[, ;]/', $str);

    $tagIds = [];
    foreach ($arrayTags as $tag) {
        // here you can apply trim or skipping empty tags
        $fTag = Tag::firstOrCreate(['tag_name' => $tag]);
        $tagIds[] = $fTag->id;
    }

    $task->tags()->sync($tagIds);

    return Redirect::route('user.tasks.index');
}

当然,您需要tags模型

Task关系

答案 1 :(得分:0)

我为那些感兴趣的人提供解决方案。唯一的变化是在TaskController.php中进行的。以下是包含注释的代码,以便您可以更轻松地理解它:

<?php 
public function update($id)
    {
        $str = Input::get('tag_name');
        //Split string by a regular expression
        $inputTags = preg_split('/[, ;]/', $str);

        $tt_current = Tagtask::where('id_task', $id)->get();
        $oldTaskTagsToDestroy = array();

        $tags_raw = Tag::all();
        $tags =  array();

        foreach($tt_current as $item) 
        {   //id_tag is the key with the tagtaskID as value.
            $oldTaskTagsToDestroy[$item->id_tag] = $item->id;
        }

        foreach($tags_raw as $tag) 
        {   //tag_name is the key with the tagID as value.
            $tags[$tag->tag_name] = $tag->id;
        }

        foreach($inputTags as $tag) 
        {
            if(!isset($tags[$tag]))
                /* At first in $tag lives the name of the tag that was given through
                input from a user. After that we return the id through the insertGetId() method and
                put in $tags[$tag]*/
                $tags[$tag] = DB::table('tags')->insertGetId(
                    array('tag_name' => $tag)
                );

                //for example tagtask ID 40 exists, so we don't execute the body of the if statement
            if(!isset($oldTaskTagsToDestroy[ $tags[$tag] ])){

                $data_TagTask= array(
                        'id_task' => $id,
                        'id_tag' => $tags[$tag]
                        );

                DB::table('tagtasks')->insertGetId($data_TagTask);

            } else 
                /*So we remove the key and the value of tagtask ID 40, because it's again present in the new input.
                We must do this, so that the old tasktags ID's will not be deleted from the tagtask table.*/
                unset( $oldTaskTagsToDestroy[ $tags[$tag] ] );
        }
        //And here we remove old tagtask ID's that aren't present anymore/again with the new input. So we delete them from the database.
        foreach($oldTaskTagsToDestroy as $key => $value) 
        {   
                Tagtask::destroy($value);
        }

        return Redirect::route('user.tasks.index');
    }

说实话,我得到了实习主管的帮助。我是一家建立Web应用程序的公司的实习生。我正竭尽全力成为一名优秀的程序员。