问题
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
There is the model relationships :
On AttributeType.php
public function category() {
return $this->belongsToMany('App\AttributeTypeCategory', 'attribute_type_category', 'attribute_type_id', 'category_id');
}
On AttributeTypeCategory.php
public function category() {
return $this->belongsToMany('App\Category');
}
All seems to be fine, but I get the following error :
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 !
回答1:
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
attribute_type - id name
category - id name description
attribute_type_category - attribute_type_id category_id
then you will create two classes (attribute_type and category) no need to create third one for the relation.
and in attribute_type you should define method for the category relation
public function category() {
return $this->belongsToMany('App\Category');}
and in category class:
public function attributeType() {
return $this->belongsToMany('App\AttributeType');}
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
you should follow laravel official documentation to learn more about relations https://laravel.com/docs/5.4/eloquent-relationships
来源:https://stackoverflow.com/questions/43527886/laravel-1066-not-unique-table-alias-on-a-relationship