0

我是 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, )) 

请有人指出我做错了什么?

4

2 回答 2

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

您正在加入没有别名的同一张表,以使它们之间有所不同。

于 2013-07-28T13:01:42.327 回答
0

问题看起来像两个表一次映射到同名 sub_category 。

多对多关系需要 3 个需要不同名称的表(类别/子类别/类别子类别)。如果其中两个表使用相同的名称进行映射,您将收到所显示的错误。

更改其中一个映射,您应该可以启动并运行。

于 2013-07-28T13:47:38.000 回答