gpt4 book ai didi

php - Laravel - 1066 关系中的表/别名不是唯一的

转载 作者:行者123 更新时间:2023-12-02 17:20:04 25 4
gpt4 key购买 nike

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

- 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]: 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)

你有什么想法吗?谢谢!

最佳答案

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

  • 属性类型 -ID姓名

  • 类别 -ID姓名描述

  • attribute_type_category -attribute_type_idcategory_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

关于php - Laravel - 1066 关系中的表/别名不是唯一的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43527886/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com