[英]Detaching Rows in Pivot Table - 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>
使用子查詢:
DELETE FROM country_team
WHERE team_id = (SELECT id FROM Team WHERE name = 'Real Madrid')
()中的選擇將返回“皇家馬德里”團隊2的ID。因此,如果team_id == 2,它將刪除country_team中的條目。
好吧,您只需傳遞country_id和team_id即可更新您的刪除小組。
public function deleteTeam(Scountry_id,$team_id)
{
$country = Country::findOrFail($country_id);
$country->teams()->detach($team_id);
}
我個人使用這樣的想法來分離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'
]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.