With Eloquent, how to filter with 2 fields (ids) ?
Hi,
I have 3 tables:
A row in the table Images has 2 specific fields:
With my setup, I can get all images by a given country like this
Country::where('name', $country_name)->first()->images
And I can get all images by a given city like this
City::where('name', $city_name)->first()->images
With Eloquent, how can I get all images by country AND city ?
(Without using PHP loops or Query Builder)
In my case, cities and countries are not related.
What I want is an "Eloquent representation" of this SQL query :
select * from images where country_id = XXX and city_id = YYY
Is there any built-in (and simpler) way to achieve it other than this:
$country = Country::where('name', $country_name)->first();
$city = City::where('name', $city_name)->first();
Image::where('country_id', $country->id)->where('city_id', $city->id);
Your Eloquent models are probably singular rather than plural:
Image::where('city_id', $city_id)->where('country_id', $country_id)->get();
Eloquent way :
Images::whereHas('country', function ($query) use($country_id) {
$query->where('country_id, $country_id);
})->whereHas('city', function ($query) use($city_id) {
$query->where('city_id, $city_id);
})->get();
@bestmomo your query is way too complex and not correct for what was requested. The query I gave will build the exact query that was asked for.
Okay,
I was looking for something like bellow, but I guess a such function doesn't exist?
Image::whereForeign('countries', 'name', $country_name)->whereForeign('cities', 'name', $city_name);
@tykus_ikus : the question is how to do with Eloquent, there is no simpler way with it, and why do you say it's not correct ?
@bestmomo sorry, you're right - I completely misread the OP's needs (^_^)
my apologies
Please or to participate in this conversation.