【发布时间】: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