Had*_*ien 2 php sql relationship laravel eloquent
我正在尝试在表之间创建一个简单的关系:
- attribute_type -
id
name
- category -
id
name
description
Run Code Online (Sandbox Code Playgroud)
所以我创建了一个数据透视表来链接它们:
- attribute_type_category -
attribute_type_id
category_id
Run Code Online (Sandbox Code Playgroud)
有模型关系:
在 AttributeType.php 上
public function category() {
return $this->belongsToMany('App\AttributeTypeCategory', 'attribute_type_category', 'attribute_type_id', 'category_id');
}
Run Code Online (Sandbox Code Playgroud)
在 AttributeTypeCategory.php 上
public function category() {
return $this->belongsToMany('App\Category');
}
Run Code Online (Sandbox Code Playgroud)
一切似乎都很好,但我收到以下错误:
SQLSTATE[42000]:语法错误或访问冲突:1066 不是唯一的表/别名:'attribute_type_category'(SQL:select
attribute_type_category.*,attribute_type_category.attribute_type_idaspivot_attribute_type_id,attribute_type_category.category_idaspivot_category_idfromattribute_type_categoryinternal joinattribute_type_categoryonattribute_type_category.id=attribute_type_category.category_idwhereattribute_type_category.attribute_type_id= 1)
你有什么主意吗 ?谢谢 !
小智 6
当你想创建简单的多对多关系就像两个表之间attribute_type和category,你应该使用迁移像你一样创建三个表
attribute_type - id 名称
类别 - id 名称描述
attribute_type_category - attribute_type_id category_id
然后您将创建两个类(attribute_type 和 category),无需为关系创建第三个类。
并且在 attribute_type 中,您应该为类别关系定义方法
public function category() {
return $this->belongsToMany('App\Category');}
Run Code Online (Sandbox Code Playgroud)
在类别类中:
public function attributeType() {
return $this->belongsToMany('App\AttributeType');}
Run Code Online (Sandbox Code Playgroud)
然后你可以使用访问任何attribute_type的类别,->categories你可以使用访问任何类别的attributeTypes->attributeTypes
您应该按照 laravel 官方文档了解有关关系的更多信息 https://laravel.com/docs/5.4/eloquent-relationships
| 归档时间: |
|
| 查看次数: |
13715 次 |
| 最近记录: |