Laravel-1066关系上的唯一表/别名
我正在尝试在表之间创建简单的关系:
I'm trying to create a simple relationship between tables :
- attribute_type -
id
name
- category -
id
name
description
所以我创建了一个数据透视表来链接它们:
So I created a pivot table to link them :
- attribute_type_category -
attribute_type_id
category_id
存在模型关系:
在AttributeType.php
On AttributeType.php
public function category() {
return $this->belongsToMany('App\AttributeTypeCategory', 'attribute_type_category', 'attribute_type_id', 'category_id');
}
在AttributeTypeCategory.php
On AttributeTypeCategory.php
public function category() {
return $this->belongsToMany('App\Category');
}
一切似乎都很好,但是出现以下错误:
All seems to be fine, but I get the following error :
SQLSTATE [42000]:语法错误或访问冲突:1066不是唯一的
表/别名:'attribute_type_category'(SQL:选择attribute_type_category
。*,attribute_type_category
。attribute_type_id
aspivot_attribute_type_id
,attribute_type_category
。category_id
作为pivot_category_id
来自attribute_type_category
内部联接attribute_type_category
attribute_type_category
上的code>。id
=attribute_type_category
。category_id
其中attribute_type_category
。attribute_type_id
= 1)
SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'attribute_type_category' (SQL: select
attribute_type_category
.*,attribute_type_category
.attribute_type_id
aspivot_attribute_type_id
,attribute_type_category
.category_id
aspivot_category_id
fromattribute_type_category
inner joinattribute_type_category
onattribute_type_category
.id
=attribute_type_category
.category_id
whereattribute_type_category
.attribute_type_id
= 1)
您有什么主意吗?
谢谢!
Do you have any idea ? Thank you !
当您要在两个表
之间创建简单的多对多关系时 attribute_type
和 category
,
您应该像以前一样使用迁移创建三个表
when you want to create simple many to many relation between two tables
like attribute_type
and category
,
you should create three tables using migrations as you did
-
属性类型-
id
名称
attribute_type - id name
类别-
id
名称
描述
category - id name description
attribute_type_category-
attribute_type_id
category_id
attribute_type_category - attribute_type_id category_id
然后,您将创建两个类(attribute_type和category),而无需为该关系创建第三个类。
then you will create two classes (attribute_type and category) no need to create third one for the relation.
,并且在attribute_type中,您应该定义类别关系的方法
and in attribute_type you should define method for the category relation
public function category() {
return $this->belongsToMany('App\Category');}
并在类别类中:
public function attributeType() {
return $this->belongsToMany('App\AttributeType');}
,然后您可以使用->类别,则可以使用-> attributeTypes
and then you can access the categories of any attribute_type by using ->categories
and you can access the attributeTypes of any category by using ->attributeTypes
您应该阅读laravel官方文档以了解有关关系的更多信息。
https ://laravel.com/docs/5.4/eloquent-relationships
you should follow laravel official documentation to learn more about relations https://laravel.com/docs/5.4/eloquent-relationships