【发布时间】:2018-03-06 16:06:08
【问题描述】:
我即将完成我的 CMS,但我有一个小问题。
我可以创建几个团队,效果很好。
我可以制作几款游戏,效果也很好。
现在我想在这些团队之间创建比赛,这意味着我有两个数据透视表。
一个叫game_match,另一个叫match_team。
game_match由game_id和match_id组成
match_team由match_id、team1_id和team2_id组成
我的match/create.blade.php 每个团队都有两个下拉字段。
保存到数据库的单个关系对我来说很好,因为我已经这样做了几次,但我不知道如何保存两个关系。
这是我目前得到的:
内部match/create.blade.php
<div class="field m-t-20 is-inline-block">
<p class="control">
<label for="home" class="label"><b>{{ trans_choice('messages.home', 1) }}</b></label>
<input type="hidden" name="home" id="home" :value="homeSelected">
<div class="select">
<select v-model="homeSelected">
@foreach($teams as $team)
<option value="{{ $team->id }}">{{ $team->name }}</option>
@endforeach
</select>
</div>
</p>
</div>
<div class="field m-t-20 is-inline-block">
<p class="control">
<label for="opponent" class="label"><b>{{ trans_choice('messages.opponent', 1) }}</b></label>
<input type="hidden" name="opponent" id="opponent" :value="opponentSelected">
<div class="select">
<select v-model="opponentSelected">
@foreach($teams as $team)
<option value="{{ $team->id }}">{{ $team->name }}</option>
@endforeach
</select>
</div>
</p>
</div>
@section('scripts')
<script>
var app = new Vue({
el: '#app',
data: {
homeSelected: "",
opponentSelected: "",
gameSelected: ""
}
});
</script>
@endsection
MatchController.php
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required|max:255',
'matchday' => 'required',
]);
$match = new Match();
$match->title = $request->title;
$match->matchday = $request->matchday;
if ($match->save()) {
$match->games()->sync($request->game);
$match->teams()->sync( [
['team1_id' => $request->home, 'team2_id' => $request->opponent],
]);
Session::flash('success', trans('messages.created', ['item' => $match->title]));
return redirect()->route('matches.show', $match->id);
} else {
Session::flash('error', trans('messages.error'));
return redirect()->route('matches.create')->withInput();
}
}
match.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Match extends Model
{
use SoftDeletes; // <-- Use This Instead Of SoftDeletingTrait
protected $fillable = [
'title'
];
protected $dates = ['deleted_at'];
public function setHomeTeam () {}
public function teams () {
return $this->belongsToMany('App\Team', 'match_team', 'match_id', 'team1_id');
}
public function games () {
return $this->belongsToMany('App\Game', 'game_match');
}
public function getHomeTeam() {
return $this->belongsToMany('App\Team', 'match_team', 'match_id', 'team1_id');
}
public function getOpponentTeam() {
return $this->belongsToMany('App\Team', 'match_team', 'match_id', 'team2_id');
}
}
有人可以帮我吗?
【问题讨论】:
标签: laravel pivot-table relationship