我有一个带有父ID和子category_id的自引用表,这个查询有SQL:
SELECT a.id, a.name, b.name, a.created_at
FROM shop_categories a
LEFT JOIN shop_categories b ON (a.id = b.category_id)
WHERE a.category_id = 0
我正在尝试将其转换为Laravel Query Builder语言,我设法提出了这个,但它不起作用,我不知道我做错了什么,我的laravel查询:
$shopcategories = DB::table('shop_categories as a')
->select('a.id', 'a.name','b.name','a.created_at')
->leftJoin('shop_categories as b', function ($join) {
$join->on('a.id', '=', 'b.category_id');
})
->where('a.category_id', '=', 0)
->get();
提前致谢。
答案 0 :(得分:3)
以这种方式使用查询构建器:
DB::table('table1')
->leftJoin('table2', 'table1.columnX', '=', 'table2.columnY')
->where('table1.other_column', '=', 'someValue')
->select('table1.columnA as NewColumn1', 'table1.columnB as NewColumn2', 'table1.columnC as NewColumn3', 'table2.columnP4 as NewColumn', 'table2.columnQ as NewColumn5')
->get();