Hadrien
Hadrien

Reputation: 23

Laravel - 1066 Not unique table/alias on a relationship

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 !

Upvotes: 2

Views: 15865

Answers (1)

Ameer Salah Aldeen
Ameer Salah Aldeen

Reputation: 289

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

Upvotes: 6

Related Questions