【发布时间】:2017-08-06 20:02:39
【问题描述】:
我以这种方式为 Mall 和 City 模型设置了关系:
商城模型:
public function city() {
return $this->belongsTo('App\City');
}
城市模型:
public function malls() {
return $this->hasMany( 'App\Mall' );
}
我在 City 类中有一个方法,它返回附近半径内的所有城市:
public function getNearby($lat, $long, $r) {
// return array of id of cities in $r radius
}
当我想获得附近城市的所有购物中心时,我会这样做:
function getMallsInNearby() {
$city_ids = City::getNearby($lat, $long, $r');
$all_malls = Mall::all();
foreach ( $all_malls as $mall ) {
$malls[] = (in_array($mall->city->id , $city_ids) ? $mall : null);
}
return array_filter($malls);
}
我尝试在商场和城市中使用 whereHas() 方法,但没有成功。 在 Laravel 中使用 Eloquent 关系实现这一目标的最佳方法是什么?
【问题讨论】:
-
你在这里打错了
getNearby($lat, $long, $r');你有多余的单引号。