[英]laravel relation using MySQL join
I have a relation in my Product Model and it's working fine我的产品 Model 有关系,它工作正常
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
asparent_id
fromproducts
inner joincategories
onproducts
.category_id
=categories
.id
inner joincategories
oncategories
.parent_id
=categories
.id
whereproducts
.id
= 13 limit 1)语法错误或访问冲突:1066 不是唯一的表/别名:'categories'(SQL:select
products
.category_id
,categories
.id
asparent_id
fromproducts
inner joincategories
onproducts
.category_id
=categories
.id
inner joincategories
oncategories
.parent_id
=categories
.id
whereproducts
.id
= 13 限制 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
.注意:希望您从
cate1
的parent_id
。 if not please, feel free to change the alias name to appropriate.如果不是,请随时将别名更改为适当的名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.