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


Deleting rows and insert row in pivot table laravel

嗨,当出现以下情况时,我正在尝试更新我的标签任务表(透视表):

例如,我们已经有了一个有3个标签的任务,例如营销、开发、会计。现在,我们要编辑该任务,删除这3个标签,并添加一个名为"烹饪"的标签。

所以我已经想到的是从标签任务表中删除这3个标签,并添加标签"烹饪"在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个标记(如前所述),并添加一个新的标记进行更新。然后,新标签被存储在标签任务表和标签表中,但问题是旧的3个标签仍在标签任务表格中。虽然它们应该被移除。。有人能帮我吗?很高兴我在等你的答复。不管怎样,谢谢你的回答。

您应该使用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');
}

当然,对于Task型号,您需要有tags关系

我为感兴趣的人提供了解决方案。唯一的更改是在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');
    }

老实说,我得到了实习主管的帮助。我是一家开发网络应用程序的公司的实习生。我正在尽我最大的努力成为一名优秀的程序员。