繁体   English   中英

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

[英]Deleting rows and insert row in pivot table laravel

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

例如,我们已经有一个带有3个标签的任务,例如市场营销,开发,会计。 现在,我们要编辑该任务并删除这3个标签,并添加1个标签,称为烹调。

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

不幸的是,关于第一部分,我没有想到。 为了向您展示我所尝试的内容,我将首先向您展示我的观点的一段代码:

{{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表中。 虽然应该将其删除。.有人可以帮我吗? 很高兴我在等待您的答复。 无论如何,谢谢您的回答。

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

老实说,我已经得到实习主管的帮助。 我是一家构建Web应用程序的公司的实习生。 我正在尽力成为一名优秀的程序员。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM