0

I have a relation in my Product Model and it's working fine

        self::where('products.id', '=', $id)
        ->select('products.category_id', 'main_categories.id as main_category_id')
            ->join('categories', 'products.category_id', '=', 'categories.id')
                ->join('main_categories', 'categories.main_category_id', '=', 'main_categories.id')
                    ->first();

i have replaced it with

        self::where('products.id', '=', $id)
        ->select('products.category_id', 'categories.id as parent_id')
            ->join('categories', 'products.category_id', '=', 'categories.id')
                ->join('categories', 'categories.parent_id', '=', 'categories.id')
                    ->first();

Now i get this error

Syntax error or access violation: 1066 Not unique table/alias: 'categories' (SQL: select products.category_id, categories.id as parent_id from products inner join categories on products.category_id = categories.id inner join categories on categories.parent_id = categories.id where products.id = 13 limit 1)

Rp9
  • 1,955
  • 2
  • 23
  • 31

1 Answers1

1

You are using same table two times for joining without using any alias names.

please refer the below code

self::where('products.id', '=', $id)
        ->select('products.category_id', 'cate1.id as parent_id')
            ->join('categories as cate1', 'products.category_id', '=', 'cate1.id')
                ->join('categories as cate2', 'cate1.parent_id', '=', 'cate2.id')
                    ->first();

NOTE: hope, the parent_id you refered from cate1. if not please, feel free to change the alias name to appropriate.

Sandeep Sudhakaran
  • 1,072
  • 2
  • 9
  • 22