我试图在一个视图中显示2个变量
{{$ match-> title}}和{{$ distance-> unit}}
但是当我dd()时,只有$ match起作用,而$ distance返回null。它。
我已经尝试过这样做,但是$ distances仍然使我为空
$matches = BikeGame::find($request->id);
$distances = Distance::find($request->id);
$matches = BikeGame::where('id',$request->id)->first();
$distances = Distance::where('id',$request->id)->first();
$matches = BikeGame::find($request->get('id'));
$distances = Distance::find($request->get('id'));
我的BikeGame模型:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class BikeGame extends Model
{
protected $guarded = [];
public function distances(){
return $this->hasMany('App\Distance');
}
}
我的距离模型:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Distance extends Model
{
protected $guarded = [];
public function bikegames(){
return $this->belongsTo('App\BikeGame');
}
}
我的控制器:
public function bikeGamesMatch(Request $request){
$matches = BikeGame::find($request->id);
$distances = Distance::find($request->id);
dd($distances);
return view('bike_games.match', compact("matches","distances"));
}
我希望我的视图显示此内容
<th scope="col" class="text-center"><strong>Game Title:</strong>
@foreach($matches as $match)
{{ $match->title }}
@endforeach
</th>
<th scope="col" class="text-center"><strong>Target: Distance</strong>
@foreach($distances as $distance)
{{ $distance->distance }} {{ $distance->unit }}
@endforeach
</th>
答案 0 :(得分:0)
尝试使用您在模型中定义的关系。
在您的控制器中:
public function bikeGamesMatch(Request $request)
{
$match = BikeGame::find($request->id); // note is just one object
return view('bike_games.match', compact("match"));
}
并在刀片中
<th scope="col" class="text-center">
<strong>Game Title:</strong>
{{ $match->title }}
</th>
<th scope="col" class="text-center">
<strong>Target: Distance</strong>
@foreach($match->distances as $distance)
{{ $distance->distance }} {{ $distance->unit }}
@endforeach
</th>
编辑
BikeGame模型:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class BikeGame extends Model
{
protected $guarded = [];
public function distance(){
return $this->belongsTo('App\Distance', 'distance_id');
}
}
距离模型:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Distance extends Model
{
protected $guarded = [];
public function bikegames(){
return $this->hasMany('App\BikeGame'); // this could be hasOne, depending on if you are going to use the same distance for other games or not
}
}
控制器:
public function bikeGamesMatch(Request $request){
$match = BikeGame::find($request->id);
return view('bike_games.match', compact("match"));
}
查看 bike_games/match.blade.php
<th scope="col" class="text-center"><strong>Game Title:</strong>
{{ $match->title }}
</th>
<th scope="col" class="text-center"><strong>Target: Distance</strong>
@isset($match->distance)
{{ $match->distance->distance }} {{ $match->distance->unit }}
@endisset
</th>