SQL到雄辩的ORM
我希望在我的Laravel应用程序中使用一个SQL查询。 SQL查询类似于:SQL到雄辩的ORM,sql,sql-server,orm,laravel,eloquent,Sql,Sql Server,Orm,Laravel,Eloquent,我希望在我的Laravel应用程序中使用一个SQL查询。 SQL查询类似于: SELECT status, count(status) AS num FROM event_businesses WHERE event_id = ? GROUP BY status ORDER BY status ASC 到目前为止我所拥有的是 $event_businesses = EventBusiness::select('status') ->where('e
SELECT status, count(status) AS num
FROM event_businesses
WHERE event_id = ?
GROUP BY status
ORDER BY status ASC
到目前为止我所拥有的是
$event_businesses = EventBusiness::select('status')
->where('event_id', '=', $event_id)
->groupBy('status')
->orderBy('status', 'asc')->get();
我真的不知道在哪里可以将count(status)as num
aggregate添加到我的ORM查询中
提前谢谢 您可能需要执行以下操作:
$event_businesses = EventBusiness::select(DB::raw('status as status, count(status) as count'))
->where('event_id', '=', $event_id)
->groupBy('status')
->orderBy('status', 'asc')->get();
您可能需要执行以下操作:
$event_businesses = EventBusiness::select(DB::raw('status as status, count(status) as count'))
->where('event_id', '=', $event_id)
->groupBy('status')
->orderBy('status', 'asc')->get();
嗨,安东妮亚,这很有效。但是有没有办法避免DB::raw?据我所知,Laravel仍然不支持结果列上的聚合函数。但您可以在整个结果集上使用聚合:
$users=DB::table('users')->count()代码>可以在原始查询中创建SQL注入点。因此,最好让sql builder为您构建查询。不过,在这种情况下,不会发生注入攻击,因为您没有使用DB::raw插入任何变量。现在,您可以使用Eloquent的selectRaw()
,whereRaw()
,orderByRaw()
和havingRaw()
方法安全地使用参数绑定强制转换原始查询。“原始方法”下的细节:嗨,安东尼娅,这很有效。但是有没有办法避免DB::raw?据我所知,Laravel仍然不支持结果列上的聚合函数。但您可以在整个结果集上使用聚合:$users=DB::table('users')->count()代码>可以在原始查询中创建SQL注入点。因此,最好让sql builder为您构建查询。不过,在这种情况下,不会发生注入攻击,因为您没有使用DB::raw插入任何变量。现在,您可以使用Eloquent的selectRaw()
,whereRaw()
,orderByRaw()
和havingRaw()
方法安全地使用参数绑定强制转换原始查询。“原始方法”下的详细信息: