mardi 27 octobre 2015

Laravel join query confusion

Very new to laravel and trying to do something simple but keep getting stuck. I have 3 tables

countries:
    id
    country

regions:
    id
    region
    country_id

wineries:
    id
    winery
    country_id
    region_id 

joined together as follows:

public function index()
{   
$wineries = Country::join('wineries', 'countries.id', '=', 'wineries.country_id')
    ->join('regions', 'regions.id', '=', 'wineries.region_id')
    ->select('countries.*')
    ->orderBy('countries.country', 'asc')
    ->get() 
    ->unique();
return view('winery.index', compact('wineries'));
}

I'm trying to return a table organized by country with each winery listed along with it's region. Countries without wineries are not to be displayed. My Index page, looks like this:

   <tbody>
        @foreach ($wineries as $country)
        <tr>
            <td colspan="2">{{ $country->country }}</td>
        </tr>
        @foreach ($country->wineries as $winery)
            <tr>
                <td>{{ $winery->winery }}</td> 
                <td>{{ $winery->region }}</td> 
            </tr>   
        @endforeach     
        @endforeach     
    </tbody>

All works well except I can't get the associated region for each winery since the region is not a part of the $winery array. Any advice on how to make it a part of array or how to accomplish this using a different query?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1WhB1me
via IFTTT

Aucun commentaire:

Enregistrer un commentaire