Laravel - 1066 Not unique table/alias on a relationship

懵懂的女人 提交于 2020-05-15 22:44:16

问题


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 as pivot_attribute_type_id, attribute_type_category.category_id as pivot_category_id from attribute_type_category inner join attribute_type_category on attribute_type_category.id = attribute_type_category.category_id where attribute_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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!