【问题标题】:Laravel - 1066 Not unique table/alias on a relationshipLaravel - 1066 关系上不是唯一的表/别名
【发布时间】:2017-09-17 13:57:06
【问题描述】:

我正在尝试在表之间创建一个简单的关系:

- 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:选择 attribute_type_category.*, attribute_type_category.attribute_type_idpivot_attribute_type_id, attribute_type_category.category_idpivot_category_id from attribute_type_category 内连接 attribute_type_category attribute_type_category.id = attribute_type_category.category_id 在哪里 attribute_type_category.attribute_type_id = 1)

你有什么想法吗? 谢谢!

【问题讨论】:

    标签: php sql laravel eloquent relationship


    【解决方案1】:

    当您想在两个表之间创建简单的多对多关系时 比如attribute_typecategory, 您应该像以前一样使用迁移创建三个表

    • attribute_type - ID 姓名

    • 类别 - ID 姓名 说明

    • attribute_type_category - 属性类型标识 category_id

    然后您将创建两个类(attribute_type 和类别),无需为关系创建第三个。

    在attribute_type中你应该定义类别关系的方法

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

    在类别类中:

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

    然后你可以使用->categories访问任何attribute_type的类别,你可以使用->attributeTypes访问任何类别的attributeTypes

    您应该关注 laravel 官方文档以了解有关关系的更多信息 https://laravel.com/docs/5.4/eloquent-relationships

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-08
      • 2020-03-06
      • 1970-01-01
      相关资源
      最近更新 更多