我正在尝试在表之间创建简单的关系:
- attribute_type -
id
name
- category -
id
name
description
所以我创建了一个数据透视表来链接它们:
- attribute_type_category -
attribute_type_id
category_id
有模型关系:
在 AttributeType.php 上
public function category() {
return $this->belongsToMany('App\AttributeTypeCategory', 'attribute_type_category', 'attribute_type_id', 'category_id');
}
关于 AttributeType Category.php
public function category() {
return $this->belongsToMany('App\Category');
}
一切似乎都很好,但我收到以下错误:
SQLSTATE[42000]:语法错误或访问冲突:1066 不唯一
表/别名:'attribute_type_category'(SQL:选择attribute_type_category
.*,
attribute_type_category
.attribute_type_id
as
pivot_attribute_type_id
, attribute_type_category
.category_id
as
pivot_category_id
from attribute_type_category
内部联接attribute_type_category
on attribute_type_category
.id
=
attribute_type_category
.category_id
在哪里attribute_type_category
.attribute_type_id
= 1)
你有什么主意吗 ?
谢谢 !
当您想在两个表之间创建简单的多对多关系时
喜欢attribute_type
and category
,
您应该像您一样使用迁移创建三个表
属性类型-
ID
姓名
类别 -
ID
姓名
描述
属性类型类别 -
属性类型id
类别_id
那么您将创建两个类(attribute_type 和category),无需为关系创建第三个类。
在 attribute_type 中,您应该定义类别关系的方法
public function category() {
return $this->belongsToMany('App\Category');}
并在类别类中:
public function attributeType() {
return $this->belongsToMany('App\AttributeType');}
然后您可以使用以下方法访问任何 attribute_type 的类别->categories
您可以使用以下方法访问任何类别的 attributeTypes->attributeTypes
您应该关注 laravel 官方文档以了解有关关系的更多信息https://laravel.com/docs/5.4/eloquent-relationships https://laravel.com/docs/5.4/eloquent-relationships
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)