dousuochu7291 2017-11-13 07:50
浏览 29
已采纳

在数据透视表中分离行 - Laravel

I have a pivot table country_team with data in this form

country_team

 country_id    team_id  
     1            1
     1            2

Country

   id    name 
    1    Spain 

Team

 id     name
  1     Barcelona
  2     Real Madrid

In my table, i have it displayed in this form

Table

 Country_id    Team
     1         Barcelona
     1         Real Madrid

Now, i want to detach real Madrid from the row but how can get the id of real madrid or get the name Real Madrid to detach it. I cannot delete using country_id since it will delete all teams belonging to that particular country .

Controller

public function index()
{
    $countries = Country::where('id',Auth::user()->id)->get();

    return view('admin.order.index',compact('orders'));
}

public function deleteTeam()
{
    $get_country_id = Country::findOrFail($id);  
    $get_country_id->teams()->detach();  
}

HTML

<tbody>
    @foreach($countries as $country)
        @foreach($country->teams as $team)
        <tr>
            <td>{{$country->id }}</td>
            <td>{{ $team->name}}</td>
        </tr>
        @endforeach
    @endforeach
</tbody>
  • 写回答

3条回答 默认 最新

  • douzhimao8656 2017-11-13 08:25
    关注

    I personally use somethink like this to detach ids.
    Controller

    public function deleteTeam($country_id, $team_id)
    {
        $country = Country::findOrFail($country_id);  
        $country->teams()->detach($team_id);
    }
    

    HTML

    <tbody>
        @foreach($countries as $country)
            @foreach($country->teams as $team)
                <tr>
                    <td>{{ $country->id }}</td>
                    <td>{{ $team->name }}</td>
                    <td>
                        <form action="{{ route('admin.team.delete', ['country_id' => $country->id, 'team_id' => $tem->id]) }}" method="post">
                            <button type="submit" role="button">Delete</button>
                            {{ csrf_field() }}
                        </form>
                    </td>
                </tr>
            @endforeach
        @endforeach
    </tbody>
    

    And in your web.php you have to add the route in the correct group or something.

    Route::post('delete/{country_id}/{team_id}', [
        'uses' => 'ControllerName@deleteTeam',
        'as' => 'admin.team.delete'
    ]);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 onlyoffice编辑完后立即下载,下载的不是最新编辑的文档
  • ¥15 求caverdock使用教程
  • ¥15 Coze智能助手搭建过程中的问题请教
  • ¥15 12864只亮屏 不显示汉字
  • ¥20 三极管1000倍放大电路
  • ¥15 vscode报错如何解决
  • ¥15 前端vue CryptoJS Aes CBC加密后端java解密
  • ¥15 python随机森林对两个excel表格读取,shap报错
  • ¥15 基于STM32心率血氧监测(OLED显示)相关代码运行成功后烧录成功OLED显示屏不显示的原因是什么
  • ¥100 X轴为分离变量(因子变量),如何控制X轴每个分类变量的长度。