2017-04-20 46 views
0

我試圖創建表之間的簡單關係1066不是唯一的表/別名:Laravel - 上的關係

- 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'); 
} 

在AttributeTypeCategory.php

public function category() { 
    return $this->belongsToMany('App\Category'); 
} 

一切似乎都很正常,但我得到了以下錯誤:

SQLSTATE [42000]:語法錯誤或訪問衝突:1066不是唯一 表/別名:'attribute_type_category'(SQL:select attribute_type_category。*, attribute_type_categoryattribute_type_id as pivot_attribute_type_idattribute_type_categorycategory_id as pivot_category_id from attribute_type_category inner join attribute_type_category on attribute_type_categoryid = attribute_type_categorycategory_id其中 attribute_type_categoryattribute_type_id = 1)

你有什麼想法嗎? 謝謝!

當你想創建簡單的多兩個表 像attribute_type和類別, 之間有許多關係,你應該使用遷移像你一樣創建三個表

回答

1

- attribute_type - ID 名

  • 類別 - ID 名 描述

    attribute_type_category - ATTRIB ute_type_id CATEGORY_ID

,那麼你將創建兩個類(attribute_type和類別)無需創建第三個的關係。

和在attribute_type你應該爲類別關係

public function category() { 
return $this->belongsToMany('App\Category');} 

和類別類中定義的方法: -

public function attributeType() { 
return $this->belongsToMany('App\AttributeType');} 

,然後可以通過使用訪問任何attribute_type的類別 - >類別 和你駕駛室通過訪問任何類型的attributeTypes - > attributeTypes

你應該遵循laravel關閉官方文件瞭解更多關係 https://laravel.com/docs/5.4/eloquent-relationships