【发布时间】:2019-06-13 02:38:24
【问题描述】:
我正在使用 Laravel 5.7 和 mysql。我有一个services 表和一个allowed_locations 表,其中包含每个城市可用的服务。 1 个服务可以在 1 个或多个城市提供。每个城市属于一个州,每个州属于一个国家。我想返回服务、城市、州和国家,但我不确定如何在每个模型中设置关系。我可以检索城市、州和国家吗?
城市
id
state_id
国家
id
country_id
name
国家
id
name
服务
id
name
Allowed_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');
}
cities.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');
}
Countries.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
},
}
}
}
【问题讨论】:
标签: laravel laravel-5 eloquent