I have two tables with a pivot table
tours
id | name | country_id | featured
countries
id | name
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With