我用这种方式建立了购物中心和城市模型的关系:
商场模式:
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()方法,但没有成功。在关系雄辩的拉勒维尔,什么是实现这一目标的最佳途径?
发布于 2017-03-15 21:41:51
使用whereIn()。
$city_ids = City::getNearby($lat, $long, $r');
$malls = Mall::whereIn('city_id', $city_ids);看看那些医生..。你几乎可以做任何事。https://laravel.com/docs/5.4/queries
希望这能有所帮助
https://stackoverflow.com/questions/42820657
复制相似问题