【问题标题】:Laravel hasMany through belongsTo relationshipLaravel 有很多通过 belongsTo 关系
【发布时间】:2019-06-27 03:07:05
【问题描述】:

是否可以通过兄弟模型的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');
}

【问题讨论】:

    标签: laravel eloquent has-many-through


    【解决方案1】:

    默认情况下,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');
    }
    

    【讨论】:

    • 这确实返回 wheels 但是,id 或每个 wheel 设置为 carid。如何让wheel 实例维护自己的 ID?
    猜你喜欢
    • 2020-01-15
    • 2017-09-03
    • 1970-01-01
    • 2019-07-22
    • 1970-01-01
    • 1970-01-01
    • 2014-07-10
    • 2014-02-12
    • 2015-08-05
    相关资源
    最近更新 更多