【问题标题】:Laravel has many throughLaravel 有很多通过
【发布时间】:2020-03-10 14:02:04
【问题描述】:

我的桌子

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...
        );

我认为 cmets 不正确的地方。根据我的经验,本地键在外键之前。

【问题讨论】:

  • 我认为您的函数中的参数顺序错误。 return $this->hasManyThrough('App\Models\ProductColor', 'App\Models\Product', 'product_id', 'product_color_id','id', 'id');
  • 你试过... 'product_id', 'product_color_id', 'id', 'id')吗?如果文档建议这样做,即使您不同意,您也应该这样做。此外,如果您在表中使用id 列,则可以省略'id', 'id';这些参数是可选的,如果你使用的是默认的,你不需要指定它。

标签: database laravel eloquent relationship has-many-through


【解决方案1】:

查看您的数据库似乎从颜色到产品的关系是多对多的,代码应该是 产品型号:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-03
    • 2016-09-18
    • 2019-06-27
    • 1970-01-01
    • 2019-07-22
    • 1970-01-01
    • 2012-03-17
    • 1970-01-01
    相关资源
    最近更新 更多