What is the purpose of using ->groupBy('games.id')? ID in games table is a primary key, right?
Dec 9, 2017
1
Level 1
Laravel select data after Join 3 tables
Hello, i have problem with selecting data from 3 tables that has relationship to each other in Laravel 5.2. First, i have 3 tables:
games('id','name','price','image') transactions('id','user_id','game_id','date') rates('id','user_id','game_id','rating') I want to select the games that users have bought (in Transaction) and also the detail of the games and the average rating of each games.
This is my code :
public function indexMyGames()
{
$trans = DB::table('transactions')
->join('games', 'games.id', '=', 'transactions.game_id')
->join('rates','rates.game_id','=','games.id')
->select('transactions.*','games.name','games.image',DB::raw('AVG(rates.rating) as average_rate'))
->groupBy('games.id')
->where('transactions.user_id','=',Auth::user()->id)
->get();
return view('games.mygames',['trans' => $trans]);
}
and i called the function:
@foreach($trans as $tran)
<div style="margin: 10px;padding: 5px 10px 5px 10px;width: 23%;border: 1px solid lightgrey;float: left;">
<img src="{{ asset('/games/' . $tran->image) }}" width="250px" height="350px">
<div style="padding-top: 5px;">
<p><label>{{$tran->name}}</label></p>
<p>Rating : {{round($tran->average_rate)}}/5</p>
</div>
</div>
@endforeach
The result is only 1 data only, it gives me only 1 game while the result should be 3 game. Can anyone tell me what's wrong? Thank you.
Please or to participate in this conversation.