-
Notifications
You must be signed in to change notification settings - Fork 8
Scopes
The scopes are very useful to craft queries with ease. However there are some important aspects to be beware of when using them.
Many of the scopes use table joins to fetch relevant data from other tables. Often we need extra information such as administrative region of a city etc.
When a table join is made, eloquent does not automatically assign aliases (AFAIK). This normally causes 'is ambiguous' errors if tables have fields with same names. Therefore the scopes in geonames package try to add meaningful aliases to tables.
As a rule of thumb, the table name is snake-case of the scop name. Eg. GeonamesGeoname::CountryInfo()
scope joins geonames_country_infos table as country_info
After using ->CountryInfo() scope. If you want to access to 'currency_code' field in the 'geonames_country_infos' table, for field name, you must use 'country_info.currency_code'
->addSelect(
'country_info.currency_code as country_info_currency_code'
);
I recommend using the snake-case convention for defining an alias for the field as well. Otherwise you may end up with same named fields in results.
You may have to use the alias when using other functions also. Such as ->orderBy()
>>> GeonamesGeoname::city('Tur%')->admin1()->countryInfo()->orderBy('population')->get();
Illuminate\Database\QueryException with message 'SQLSTATE[23000]: Integrity constraint violation:
1052 Column 'population' in order clause is ambiguous (SQL: ...)'
>>>
This happens because both 'geonames_geonames' and 'geonames_country_infos' tables cointain a 'population' field. Therefore you have to tell exactly which one to use. You have two choices, either use ->orderBy('geonames_geonames.population')
or ->orderBy('country_info.population')
Wiki
Quickstart
Models
Examples