Laravel的hasMany通过属于关联关系

问题描述 投票:0回答:1

是否有可能通过同级模型的hasMany关系检索父模型的belongsTo关系。我有以下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');
}
laravel eloquent has-many-through
1个回答
2
投票

默认情况下,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');
}
© www.soinside.com 2019 - 2024. All rights reserved.