Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel query builder with pivot table

I have two tables with a pivot table

Table tours

id | name | country_id | featured

Table countries

id | name

Pivot Table country_tour

id | country_id | tour_id

I want to to find the tour that has featured column of tours table set to 1 and country_id of country_tour table set to 1.

like image 893
Zachary Dale Avatar asked Nov 17 '16 16:11

Zachary Dale


1 Answers

UPDATED:

You can do it like this using Laravel's query Builder method - whereHas():

Your models should look like this (Many to Many Relationships):

Tour Model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Tour extends Model
{
    public function countries() {
      return $this->belongsToMany('App\Country');
    }
}

and Country Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Country extends Model
{
    public function tours() {
      return $this->belongsToMany('App\Tour');
    }
}

and now you can fetch the desired results by using the below query:

Tour::where('featured', 1)
    ->whereHas('countries', function($q) {
        $q->where('id', 1);
    })
    ->get();

This will get you the collection of tours with featured = 1 and having country with id = 1.

Hope this helps!

like image 70
Saumya Rastogi Avatar answered Oct 20 '22 00:10

Saumya Rastogi