Laravel Eloquent 带中间表的多模型关联方案求解
解决方案:Laravel多对多关联下的Term模型关联配置
先把咱们的模型关系理清楚:
- Bus(巴士) 和 Destination(目的地) 是多对多关系(一辆巴士能跑多个目的地,一个目的地有多个巴士停靠)
- Term(档期) 绑定单个Bus + 单个Destination的组合(每个档期对应特定巴士去往特定目的地的日期和价格)
第一步:调整数据库表结构
除了已有的buses、destinations、terms表,你需要新增一个多对多中间表bus_destination,字段至少包含bus_id、destination_id(可选添加自增主键id)。
另外,terms表必须添加两个外键字段:bus_id(关联buses.id)、destination_id(关联destinations.id)。
第二步:编写各模型的关联方法
Bus 模型
class Bus extends Model { // 多对多关联Destination public function destinations() { return $this->belongsToMany(Destination::class); } // 直接关联该巴士的所有档期 public function terms() { return $this->hasMany(Term::class); } // 可选:快速获取该巴士到某特定目的地的档期 public function termsForDestination(Destination $destination) { return $this->terms()->where('destination_id', $destination->id); } }
Destination 模型
class Destination extends Model { // 多对多关联Bus public function buses() { return $this->belongsToMany(Bus::class); } // 直接关联该目的地的所有档期 public function terms() { return $this->hasMany(Term::class); } }
Term 模型
class Term extends Model { // 关联所属的巴士 public function bus() { return $this->belongsTo(Bus::class); } // 关联所属的目的地 public function destination() { return $this->belongsTo(Destination::class); } }
为什么不用hasManyThrough?
你之前在Bus单对应一个Destination时用了hasManyThrough,但现在是多对多场景——hasManyThrough适用于间接的一对多链(比如Bus has many Destination,Destination has many Term),但你的Term是直接绑定Bus和Destination的,所以直接用hasMany关联Term才是最准确的做法。
使用示例
比如获取某巴士的所有目的地及对应档期:
$bus = Bus::with('destinations.terms')->find(1); foreach ($bus->destinations as $destination) { echo "目的地:{$destination->name}\n"; foreach ($destination->terms as $term) { echo "日期:{$term->date},价格:{$term->price}\n"; } }
或者直接获取某巴士的所有档期:
$busTerms = Bus::find(1)->terms;
内容的提问来源于stack exchange,提问作者DominikN.
相关产品推荐
相关产品推荐

