自我加入laravel

时间:2015-11-09 10:09:26

标签: php laravel join

我已经阅读了一些相同的问题,但我没有得到任何解决方案。我有一个表名“类别”。我有三个列id,parent_id,name。我想显示带有parent_id名称的记录。

现在的记录显示为....

id   parent_id   name
1        0       Mobile
2        0       TV
3        1       Samsung

但我想......

id   parent_id         name
1        0             Mobile
2        0             TV
3        Mobile        Samsung

我尝试 ,但显示错误语法错误或访问冲突:1066不唯一的表/别名:'category'

DB::table('category')->join('category','category.id','=','category.parent_id')->where('category.parent_id','>',0)->get();

我通过此查询解决了我的问题.....

$sql = "select category1.name as name1, category2.name as name2, category1.id,category1.parent_id";
$sql .= " from category as category1 left join category as category2 on category1.id=category2.parent_id where category2.parent_id >0";
return DB::select($sql);

2 个答案:

答案 0 :(得分:1)

尝试以下查询

$result = DB::table('category as c1') 
->leftJoin('category as c2','c1.id', '=', 'c2.parent_id')
->where('c1.parent_id','>',0)->get();

答案 1 :(得分:0)

尝试以下查询

   $result = DB::table('category as c1') 
->join('category as c2','c1.id', '=', 'c2.parent_id')
select(
    'id',
    'name',
    DB::raw('( case when c1.parent_id > 0 then c2.name ELSE c1.parent_id End ) as "parent_id"'),
    ->get();