Laravel中如何通过Country关联过滤Venue模型的查询结果
基于country筛选Venue模型的实现方法
你可以选择以下两种方案实现需求:
方案1:直接嵌套关联查询(无需修改现有模型)
Laravel的whereHas支持点语法查询多层嵌套关联,适合临时单次筛选的场景,不需要改动原有代码:
$countryId = 1; // 替换为实际要筛选的国家ID,也可以用name等其他字段筛选 $venues = Venue::with(['city', 'city.country']) // 不需要预加载关联数据可以去掉这行 ->whereHas('city.country', function($query) use ($countryId) { $query->where('id', $countryId); }) ->get();
方案2:新增直通关联(复用性更高)
如果后续有多处需要直接从Venue访问关联Country的需求,可以在Venue模型中新增hasOneThrough类型的直通关联,后续使用更便捷。
第一步:修改Venue模型添加关联
class Venue extends Model { public function city() { return $this->belongsTo(City::class); } // 新增直接关联Country的直通关联 public function country() { // 表字段符合Laravel命名约定时可以只传前两个参数,不需要写后面的字段配置 return $this->hasOneThrough( Country::class, City::class, 'id', // City表主键 'id', // Country表主键 'city_id', // Venue表关联City的外键 'country_id' // City表关联Country的外键 ); } }
第二步:筛选代码
添加关联后就可以和按city筛选一样直接查询:
$countryId = 1; $venues = Venue::with('country') ->whereHas('country', function($query) use ($countryId) { $query->where('id', $countryId); }) ->get();
内容的提问来源于stack exchange,提问作者dodi restiadi
相关产品推荐
相关产品推荐

