'Laravel join multiple query result
when i run the following query, results are listed multiple.
there are 3 records in the table but it lists 5
$adverts = Advert::where("category_id", $category->id)
->where("adverts.created_at", "<=", Carbon::now())
->orderBy("id", "DESC")
->select('adverts.*', 'advert_countries.advert_id', 'advert_countries.country_id')
->join("advert_countries", "advert_countries.advert_id", "adverts.id")
->whereIn("advert_countries.country_id", $arr)->paginate(10);
---Fixed---
Model :
public function countries(){
return $this->hasMany(AdvertCountry::class, 'advert_id')->orderBy('id', "DESC");
}
Controller :
$adverts = $adverts->whereHas('countries', function($q) use ($arr){
$q->whereIn('country_id', $arr);
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
