我有两张桌子:
类别:
idCat, nameCat, urlCat
详细信息:
idDetailPost, nameDetailPost, viewDetailPost, idCat
这意味着1个类别有很多帖子。我的问题是:我需要网站上的表格:
nameCat
urlCat
count(post in category)
count(viewDetailPost)
这是SQL权利。我在XAMPP中测试了它:
SELECT
c.nameCat AS nameCategory,
c.urlCat AS urlCategory,
COUNT(d.idCat) AS countPost,
COUNT(d.viewDetailPost) AS viewPost FROM
category c,
detailpost d WHERE
c.idCat = d.idCat GROUP BY
d.idCat
但我不知道如何在Laravel 5.4中编写它。我试过DB :: raw,DB :: select,join ...请帮忙!谢谢!
答案 0 :(得分:0)
DB::table('detailpost as dp')
->leftJoin('category as c','c.id','=','dp.idCat')
->select( 'c.nameCat AS nameCategory', 'c.urlCat AS urlCategory',DB::raw('count(dp.idCat) as countPost),DB::raw('count(dp.viewDetailPost) as viewPost ))
->groupBy('dp.idCat')
->get();
答案 1 :(得分:0)
非常感谢!这是答案!
$sql = DB::table('detailpost')
->select(
'category.nameCat AS name_category',
'category.urlCat AS url_category' ,
DB::raw('count(detailpost.idCat) as count_post'),
DB::raw('count(detailpost.viewDetailPost) as view_post')
)
->leftJoin('category','detailpost.idCat','category.idCat')
->groupBy('category.nameCat', 'category.urlCat')
->orderBy('detailpost.idCat', 'ASC')
->get();