Laravel 中用 DB::写复杂的 sql 语句,遇到问题,问题是不会写了?

select cust_id,cust_name,cust_res,COUNT(cust_name) as num
FROM (select * from cust_table GROUP BY cust_name,cust_res)
GROUP BY cust_name HAVING (num<2 AND cust_res='n');

这个复杂sql语句用DB::怎么写??求教

wanghan
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 7
wanghan

别沉啊

7年前 评论

说实话,我感觉ORM的数据库引擎用起来比直接用查询构造器要舒服的多!

7年前 评论
wanghan

@Vlongen 求教用orm的写法,刚接触laravel

7年前 评论
Epona

你可以使用'DB::Raw'来写,或者使用Eloquent吧,可以多看看Eloquent的文档,还是比较简单的,先从最简单的返回,然后再逐步增加内容。

7年前 评论

@wanghan 你试下

$subQuery = DB::table('cust_table')
    ->groupBy('cust_name')
    ->groupBy('cust_res');

$info = DB::table(DB::raw("({$subQuery->toSql()}) as sub"))
    ->mergeBindings($subQuery)
    ->groupBy('cust_name')
    ->having('num', '<', '2')
    ->having('cust_res', 'n')
    ->select(
        'cust_id', 
        'cust_name', 
        'cust_res', 
        DB::raw('count(cust_name) as num')
    )->get();
7年前 评论

你这个SQL 语法很有问题吧。
SELECT cust_id,cust_res,COUNT(cust_name) as num FROM cust_table WHERE cust_res =‘n’ GROUP BY cust_name HAVING num<2
\App\Model\CustTable::select(DB::raw('count(cust_name) as num, cust_res,cust_id'))
->where('cust_res','n')
->groupBy('cust_name')
->having('num','<',2)->get();

7年前 评论
wanghan

@Nocarefree @Kerwin @Epona 谢谢你们,问题已经解决了!!!

7年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!