Laravel有很多通过

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

我的桌子

products
  - id
  - name

product_variants
  - id
  - product_id
  - color_id

product_colors
  - id
  - hex

我不会有这样的关系

Product::colors(); // get all the colors through variants

在我的Product.php模型中,有

public function colors() {
    return $this->hasManyThrough('App\Models\ProductColor', 'App\Models\Product', 'id', 'id', 'product_id', 'product_color_id');
}

这似乎不起作用。

作为旁注。在当前的laravel文档中,它提供了以下示例:

return $this->hasManyThrough(
            'App\Post',
            'App\User',
            'country_id', // Foreign key on users table...
            'user_id', // Foreign key on posts table...
            'id', // Local key on countries table...
            'id' // Local key on users table...
        );

我认为评论不正确的地方。根据我的经验,本地键位于外键之前。

database laravel eloquent relationship has-many-through
1个回答
0
投票

查看您的数据库似乎发​​现颜色与产品之间的关系是多对多的,并且代码应为产品型号:

public function colors(){
   return $this->belongsToMany('App\Models\ProductColor', 'product_variants', 'product_id', 'id')->withPivot('id');
}

ProductColors型号:

public function products(){
   return $this->belongsToMany('App\Models\Product', 'product_variants', 'id', 'product_id')->withPivot('id');
}

或者,如果您想获得更大的灵活性,请创建一个ProductVariant模型,并在Product和ProductColor上使用hasMany关系,并且在ProductVariant内部使用两个belongsTo,分别指向Product和ProductColor。>

© www.soinside.com 2019 - 2024. All rights reserved.