在1个视图中显示2个表

时间:2019-05-31 04:04:58

标签: laravel

我想在1个视图中显示2个表

像这样:

{{ $match->title }}
{{ $distance->distance }}

但是我无法正常工作。

这是我的控制者:

public function bikeGamesMatch(Request $request){ 
    $matches = BikeGame::find($request->id);
    $distances = Distance::find($request->id);
    dd($matches);                          
    return view('bike_games.match', compact("matches","distances"));
}

为什么$distancesnull返回dd()

这是我的观点:

<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>

如果执行此操作,则视图会显示404

$matches = BikeGame::find($request->id)->firstOrFail();
$distances = Distance::find($request->id)->firstOrFail();

我在这里做什么错了?

4 个答案:

答案 0 :(得分:1)

    use has one relationship between two model :: BikeGame & Distance .
    give then Unique id. like Bike_id & Distance_id.
    Bikegame model => 
    public function distance(){
            return $this->hasOne('App\Distance','Distance_id', 'id');
        }
    Distance Model => 
    public function bike()
        {
            return $this->belongsTO('App\Bikegame', 'Distance_id','id');
        }


    in your controller ex.

     $bike = BikeGame::with('distance')->find($id);
     $bike->bikename    = request('bikename');
     $bike->distance->distacekm = $request->distacekm;
     $bike->distance->dismm = $request->dismm; 

try this step

答案 1 :(得分:0)

尝试更改:

$matches = BikeGame::find($request->id);
$distances = Distance::find($request->id);

$matches = BikeGame::find($request->get('id'));
$distances = Distance::find($request->get('id');

答案 2 :(得分:0)

尝试此更改

$matches = BikeGame::where('id',$request->id)->first();
$distances = Distance::where('id',$request->id)->first();

希望它对您有用。

答案 3 :(得分:0)

在使用foreach之前先查看

isset($matches) && count(matches) >0

如果此条件成立,则使用foreach