我是laravel的新手,我坚持使用我的关系,看起来像下面的
分类
id name slug
-----------------------------------------------------------------
3 Location location
4 Outfits outfits
5 Other other
- 行业标准
id category_id name slug
-----------------------------------------------------------------------------
12 3 Club club
13 3 Home / Hotel home-hotel
14 3 Outdoor outdoor
15 3 Studio studio
16 4 Bikini / Swimwear bikini-swimwear
17 4 Dress dress
19 4 Jeans jeans
35 5 Dancing dancing
类别模型
<?php
class Category extends Eloquent {
public $timestamps = false;
public function subcategory()
{
return $this->belongsToMany('subcategory', "sub_categories");
}
}
我收到以下错误
SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'sub_categories' (SQL: select `sub_categories`.*, `sub_categories`.`category_id` as `pivot_category_id`, `sub_categories`.`subcategory_id` as `pivot_subcategory_id` from `sub_categories` inner join `sub_categories` on `sub_categories`.`id` = `sub_categories`.`subcategory_id` where `sub_categories`.`category_id` = ?) (Bindings: array ( 0 => 1, ))
可以请某人指出我做错了吗?
答案 0 :(得分:1)
您应该为同一个表提供不同的别名
更改此
inner join `sub_categories`
到
inner join `sub_categories` as sc
^^--//-this alias use it instead of sub_categories
在您的查询中将是
select `sub_categories`.*, sc.`category_id` as `pivot_category_id`, sc.`subcategory_id` as `pivot_subcategory_id` from `sub_categories` inner join `sub_categories` sc on sc.`id` = `sub_categories`.`subcategory_id` where `sub_categories`.`category_id` = ?) (Bindings: array ( 0 => 1, )
示例:
select * from table1 as t1
inner join table1 as t2
on t1.id = t2.id
澄清您的错误: Not unique table/alias
你正在加入相同的表而没有别名,它们之间的区别不同。
答案 1 :(得分:0)
问题看起来是两个表一次映射到同一个名称sub_category。
多对多关系需要3个表(category / subcategory / category_subcategory),这些表需要不同的名称。如果其中两个表使用相同的名称进行映射,则会显示您正在显示的错误。
更改其中一个映射,您应该启动并运行。