Laravel雄辩的hasmany的雄辩has

时间:2019-11-15 13:44:22

标签: laravel eloquent

制造商表

id | manufacturer_id
1  | 
2  | 1
3  | 1

零件表

id | manufacturer_id
1  | 1
2  | 2
3  | 3

零件模型:

public function manufacturer()
{
    return $this->belongsTo('App\Manufacturer');
}

制造商型号:

public function manufacturer()
{
    return $this->belongsTo('App\Manufacturer', 'manufacturer_id');
}

public function parts()
{
   return $this->hasMany('App\Part');
}

我如何在制造商模型上建立零件关系以返回制造商1的零件1,零件2和零件3?

1 个答案:

答案 0 :(得分:0)

对于制造商零件,您已经拥有正确的方法,对于“子制造商”,您必须使用https://laravel.com/docs/5.8/eloquent-relationships#has-many-through,例如:

public function childsParts(){
    return $this->hasManyThrough('App\Parts', 'App\Manifacturer');
}

但是您可能必须在hasManyThrough参数中设置外键和主键

编辑: 而不是必须合并两个集合,例如

public function allParts(){
    return $this->parts->merge($this->childsParts);
}

唯一的问题是,您要操作集合而不是Builder,因此在此之后,在其上调用的所有方法都只是php脚本而不是数据库查询。 如果您想对它进行分页,请看看此https://gist.github.com/vluzrmos/3ce756322702331fdf2bf414fea27bcb