whereHas on multiple relationships - laravel 5.4

2019-07-30 01:50发布

问题:

I have multiple tables.

Tour Table

id | title | slug .....

Image Table

id | tour_id | image.....

Inclusion Table

id | tour_id | inclusion....

Exclusion Table

id | tour_id | exclusion...

Itenary Table

id | tour_id | day_summary.....

Tour_User Table (This is a pivot table between tour table and user table)

tour_id | user_id

I Need

I want to get tour details with image, inclusion, exclusion, itenary, tour user where image.tour_id equals tour.id and inclusion.tour_id equals tour.id and exclusion.tour_id equals tour.id and so on.

I have defined relationship in Tour Model as

public function user() {
        return $this->hasOne(TourUser::class);
    }

    public function image() {
        return $this->hasMany(TourImage::class);
    }

    public function inclusion() {
        return $this->hasMany(TourInclusion::class);
    }

    public function exclusion() {
        return $this->hasMany(TourExclusion::class);
    }

    public function highlight() {
        return $this->hasMany(TourHighlight::class);
    }

    public function itenary() {
        return $this->hasMany(TourItenary::class);
    }

I know this can be done with looping and conditional statements where we need to query the database multiple times, but I want to achieve it with `eager loading with eloquent in Laravel 5.4 How can I achieve it. https://stackoverflow.com/a/21380265/4807414 this seem to have have a bit similar problem but couldn't solve.

I tried something like:

$tour = Tour::where('slug', $slug)
                    ->with('user', 'image', 'itenary', 'inclusion', 'exclusion')
                    ->whereHas('user',  function($query) {
                        $query->where('user_id', user()->id); }) <-- user() defind in helper function for logged in user detail
                    ->whereHas('itenary', function($query) {
                        $query->where('tour_id', '21'); }) <-- pass tour id
                    ->whereHas('inclusion', function($query) {
                        $query->where('tour_id', '21'); }) <-- pass tour id
                    ->first();

回答1:

You can not do something like that on Laravel because the relationship is Has Many

You should do like this :

$tour = Tour::where('slug', $slug)
->whereHas('user',  function($query) {
    $query->where('user_id', user()->id);
}) <-- user() defind in helper function for logged in user detail
->whereHas('itenary', function($query) {
    $query->where('tour_id', '21');
}) <-- pass tour id
->whereHas('inclusion', function($query) {
    $query->where('tour_id', '21');
}) <-- pass tour id
->first();

$images = $tour->image;
$inclusions = $tour->inclusion;
$exclusions = $tour->exclusion;
$highlights = $tour->highlight;
$itenaries = $tour->itenary;