Laravel |保存并显示两个关系
问题描述:
我即将完成我的CMS,但我有一个小问题。Laravel |保存并显示两个关系
我可以创建几个团队,工作完美。
我可以制作几款游戏,作品也很完美。
现在我想创建这些团队之间的匹配,这意味着我有两个数据透视表。 一个叫做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');
}
}
有人可以帮我吗?
答
您应该更好地使用firstOrCreate(),updateOrCreate或attach()方法。
这并不能解决我在保存同一外表的两个关系时遇到的问题。 – Kazuto