我试图使用左连接(在同一个表上)获取类别列表以获取父类别。
查询类似于
SELECT categories.`cat_id`, categories.`cat_name`, categories.`cat_desc`, categories.`parent_id`, categories.`created_at`,cat2.cat_name FROM `categories` JOIN categories cat2 ON categories.parent_id = cat2.cat_id
所以在Laravel雄辩中写道
$categoryModel::select('categories.cat_id', 'categories.cat_name', 'categories.cat_desc', 'categories.parent_id', 'categories.created_at','cat2.cat_name')
->leftJoin('categories AS cat2','categories.parent_id', '=' , 'cat2.cat_id')
->get();
不幸的是,结果只有第一个表格列
[{"cat_id":1,"cat_name":"Camera","cat_desc":null,"parent_id":3,"created_at":null},{"cat_id":2,"cat_name":"Camera","cat_desc":null,"parent_id":3,"created_at":null},{"cat_id":3,"cat_name":null,"cat_desc":null,"parent_id":null,"created_at":null},{"cat_id":4,"cat_name":null,"cat_desc":null,"parent_id":null,"created_at":null},{"cat_id":5,"cat_name":"CCTV","cat_desc":null,"parent_id":4,"created_at":null},{"cat_id":6,"cat_name":"CCTV","cat_desc":null,"parent_id":4,"created_at":null}]
提前致谢。 :)
答案 0 :(得分:1)
此处两个表格列都具有相同的名称,因此您需要在第二个表格的列中使用别名,请在下面更改您的查询,例如'cat2.cat_name as c_name'
$categoryModel::select('categories.cat_id', 'categories.cat_name', 'categories.cat_desc', 'categories.parent_id', 'categories.created_at','cat2.cat_name as c_name' )
->leftJoin('categories AS cat2','categories.parent_id', '=' , 'cat2.cat_id')
->get();
答案 1 :(得分:1)
它以这种方式工作,我为每列提供了别名。
$categoryModel::select('cat1.cat_id as catId', 'cat1.cat_name as catName', 'cat1.cat_desc as catDesc', 'cat1.parent_id as parId', 'cat1.created_at as cAt','cat2.cat_name as parCatName')
->from('categories as cat1')
->leftJoin('categories AS cat2','cat1.parent_id', '=' , 'cat2.cat_id')
->get();