Я использую Laravel 5.7 и mysql.У меня есть таблица services
и таблица allowed_locations
, которая показывает, какие услуги доступны в каждом городе.1 услуга может быть доступна в 1 или более городах.Каждый город принадлежит одному штату, и каждый штат принадлежит одной стране.Я хотел бы вернуть услугу, город, штат и страну, но я не уверен, как установить отношения в каждой из моделей.Могу ли я получить город, штат и страну?
Города
id
state_id
Государства
id
country_id
name
Страны
id
name
Услуги
id
name
Разрешено_Locations
city_id (id from cities table)
service_id (id from Services table)
Идентификатор страны, название 1, США
Штаты
id, country_id, name
3, 1, California
4, 1, Washington
5, 1, Oregon
Города
id, state_id, name
1, 3, San Diego
2, 4, Seattle
3, 5, Portland
Услуги
id, name
1, Tax Services
2, Legal Services
РазрешеноМестоположение
city_id, service_id
1, 1
2, 1
3, 2
Services.php модель
public function locations () {
return $this->belongsToMany('App\cities', 'services_by_location', 'service_id','city_id');
}
towns.php модель
public $with = ['state'];
public function state() {
return $this->hasOne(states::class, 'id', 'state_id');
}
states.php модель
public $with = ['country'];
public function country() {
return $this->hasOne(Countries::class, 'id', 'country_id');
}
Страны.php модель
//
AllowedLocations.php модель
//
Контроллер
$data = Services::with(['locations'])->get();
return response()->json($data, 200);
В настоящее время я возвращаю ответ, подобный этому
{
{
id: 1,
name: Tax Services
locations:
{
{
city_id: 1,
city: San Diego,
state: {
name: California
}
country: {
name: USA,
}
},
{
city_id: 2,
city: Seattle,
state: {
name: Washington
}
country: {
name: USA,
}
},
}
},
{
id: 2,
name: Legal Services
locations:
{
{
city_id: 3,
city: Portland,
state: {
name: Oregon
}
country: {
name: USA,
}
},
}
}
}
Вместо вложенных state
и country
Я хотел бы вернуть город, штат и название страны во вложенном массиве местоположений.Это возможно?
{
{
id: 1,
name: Tax Services
locations:
{
{
city_id: 1,
city: San Diego,
state: California,
country: USA
},
{
city_id: 2,
city: Seattle,
state: Washington,
country: USA
},
}
},
{
id: 2,
name: Legal Services
locations:
{
{
city_id: 3,
city: Portland,
state: Oregon,
country: USA
},
}
}
}