Laravel hasMany 通过 belongsTo 关系

Laravel hasMany through belongsTo relationship

是否可以通过兄弟模型的 belongsTo 关系检索父模型的 hasMany 关系。我有以下 Models:

汽车

public function wheels() {
  return $this->hasMany('App\Models\Wheel');
}

public function seats() {
  return $this->hasMany('App\Models\Seat');
}

轮子

// @property int|null $car_id Type: int(10) unsigned, Extra: , Default: null, Key: MUL

public function car() {
  return $this->belongsTo('App\Models\Car');
}

座位

// @property int|null $car_id Type: int(10) unsigned, Extra: , Default: null, Key: MUL

public function car() {
  return $this->belongsTo('App\Models\Car');
}

我想做的是在给定座位 ($seat->wheels) 的情况下取回汽车的车轮:

座位

public function car() {
  return $this->belongsTo('App\Models\Car');
}

public function wheels() {
  // Works
  // return $this->car->wheels;

  // What I would like to do, but doesn't work
  return $this->hasManyThrough('App\Models\Wheel', 'App\Models\Car');
}

默认情况下,HasManyThrough 是两个 HasMany 关系的组合。

在你的情况下,你必须切换第一个外键和本地键:

public function wheels() {
  return $this->hasManyThrough('App\Models\Wheel', 'App\Models\Car', 'id', null, 'car_id');
}

列覆盖存在问题,将在 Laravel 5.8 中修复:https://github.com/laravel/framework/pull/25812

同时,您可以使用BelongsToMany关系:

public function wheels() {
    return $this->belongsToMany(Wheel::class, 'cars', 'id', 'id', 'car_id', 'car_id');
}