简体   繁体   中英

Get datas from one to many (inverse ) relation laravel

I have 2 models 'Trips.php'

public function region() 
{
    return $this->belongsTo('App\Region');
}

Region.php

public function trips()
{
    return $this->hasMany('App\Trip');
}

I'm trying to show the trips that are in one one specific region. For example: I have a region named Lake Side and I want to show all trips that are in Lake Side region in list.

I tried the following:

In controller:

$trips = Trip::all();

In view:

@foreach($trips as $trip)
<li><a href="#">
    {{$trip->region->name}}</a>
    <ul class="dropdown">
        <li><a href="#">
            {{$trip->title}}</a>
        </li>    
    </ul>
</li>
@endforeach   

This gives me region name and trip name but repeats region name if more than one trip is made in same region.

And tried another way around (inverse):

<ul class="dropdown">
@foreach($regions as $region)
<li><a href="#">
    {{$region->tour->title}}</a>
</li>
@endforeach
</ul>  

And getting error Trying to get property of non-object

By getting trips with regions, what you're essentially getting is every trip with a region property.

Instead do the reverse Region::with('trips')->where('id', $regionId)->get() and you'll get regions with their trips. So now every region result has a trips property which contains many trips.

Alternatively don't use eager load. So Region::firstOrFail($regionId) then just use $region->trips .

And you can loop through them like

// Can print region here
@foreach($region->trips as $trip)
    // Can print region's trips here
@endforeach

One way to do that is to use whereHas() :

$trips = Trip::whereHas('region', function($q) use ($regionName) {
    $q->where('name', $regionName);
})->get();

Pass $trips and $regionName to the view:

@foreach ($trips as $trip)
    <li><a href="#">{{ $regionName }}</a>
        <ul class="dropdown">
            <li><a href="#">
                {{ $trip->title }}</a>
            </li>    
        </ul>
    </li>
@endforeach   

Alternatively, you can use eager loading :

$region = Region::where('name', $regionName)->with('trips')->first();

And in the view:

@foreach ($region->trips as $trip)
    <li><a href="#">{{ $region->name }}</a>
        <ul class="dropdown">
            <li><a href="#">
                {{ $trip->title }}</a>
            </li>    
        </ul>
    </li>
@endforeach  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM