一对多/反向关系-Laravel
这似乎很简单,但我似乎无法理解 我有以下几种型号 城市->有许多地点 地点->有许多餐厅 餐厅->属于地点 这意味着餐厅通过地点链接到城市 现在,我想在特定的城市中找到餐厅,这是基于提供的位置,但不限于该位置,而是基于城市 提供的值是城市名和地点名。 这样我就可以得到一对多/反向关系-Laravel,laravel,laravel-5,eloquent,Laravel,Laravel 5,Eloquent,这似乎很简单,但我似乎无法理解 我有以下几种型号 城市->有许多地点 地点->有许多餐厅 餐厅->属于地点 这意味着餐厅通过地点链接到城市 现在,我想在特定的城市中找到餐厅,这是基于提供的位置,但不限于该位置,而是基于城市 提供的值是城市名和地点名。 这样我就可以得到城市id和位置id // this will get a city with all locations $city = City::with('locations')->where('value', $c)->firs
城市id
和位置id
// this will get a city with all locations
$city = City::with('locations')->where('value', $c)->first();
$city_id = $city->id;
// this will get the location id
$location = Location::where('value', $l)->first();
$location_id = $location->id;
因此,我的$restaurants
查询应该会找到位置
属于$city
的位置
的所有餐厅
如何实现这一点?您可以通过这样的关系定义hasmany-
class City extends Model
{
public function locations()
{
return $this->hasMany('App\Location');
}
public function restaurants()
{
return $this->hasManyThrough('App\Restaurant', 'App\Location');
}
}
class Location extends Model
{
public function City()
{
return $this->belongsTo('App\City');
}
public function restaurants()
{
return $this->hasMany('App\Restaurant');
}
}
class Restaurant extends Model
{
public function location()
{
return $this->belongsTo('App\Location');
}
public function city()
{
return $this->belongsTo('App\City');
}
}
查看文档
您可以通过以下方式定义HasManyThrough关系-
class City extends Model
{
public function locations()
{
return $this->hasMany('App\Location');
}
public function restaurants()
{
return $this->hasManyThrough('App\Restaurant', 'App\Location');
}
}
class Location extends Model
{
public function City()
{
return $this->belongsTo('App\City');
}
public function restaurants()
{
return $this->hasMany('App\Restaurant');
}
}
class Restaurant extends Model
{
public function location()
{
return $this->belongsTo('App\Location');
}
public function city()
{
return $this->belongsTo('App\City');
}
}
查看文档
我的查询将是什么样子?假设
餐厅
属于城市
,这将是我将使用的查询<代码>$restaurants=Restaurant::with('restaurantClass')->where('city_id',$city_id)->get()代码>如果你想在一个城市里拥有所有的餐馆,你需要为之写一个范围。您可以像这样访问餐厅所属的城市-->$restaurant->city;我不明白你的意思。你是在找某个特定城市的所有餐馆吗?是的,我需要一个查询,根据提供的位置查找特定城市的所有餐馆。我的查询结果如何?假设餐厅
属于城市
,这将是我将使用的查询<代码>$restaurants=Restaurant::with('restaurantClass')->where('city_id',$city_id)->get()代码>如果你想在一个城市里拥有所有的餐馆,你需要为之写一个范围。您可以像这样访问餐厅所属的城市-->$restaurant->city;我不明白你的意思。你是在找某个特定城市的所有餐馆吗?是的,我需要根据提供的位置查询某个特定城市的所有餐馆