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

时间:2017-11-13 07:50:54

标签: php laravel

我有一个数据透视表country_team,其中包含此表单中的数据

country_team

 country_id    team_id  
     1            1
     1            2

国家

   id    name 
    1    Spain 

团队

 id     name
  1     Barcelona
  2     Real Madrid

在我的表格中,我以此表格显示

表格

 Country_id    Team
     1         Barcelona
     1         Real Madrid

现在,我想从这一行中分离出真正的马德里,但是如何获得真正的马德里的id或者让名字Real Madrid分离它。我无法使用country_id删除,因为它将删除属于该特定国家/地区的所有团队。

控制器

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 个答案:

答案 0 :(得分:0)

使用子查询:

DELETE FROM country_team
WHERE team_id = (SELECT id FROM Team WHERE name = 'Real Madrid')

select in()将返回team&#39; Real Madrid&#39;,2的ID。如果team_id == 2,它将删除country_team中的条目。

答案 1 :(得分:0)

您可以简单地传递country_id和team_id并更新您的删除团队。

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

答案 2 :(得分:0)

我个人使用这样的想法来分离ID 的控制器

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>

在您的 web.php 中,您必须在正确的群组中添加路线。

Route::post('delete/{country_id}/{team_id}', [
    'uses' => 'ControllerName@deleteTeam',
    'as' => 'admin.team.delete'
]);