请求将指定原生SQL转换为Laravel Eloquent查询语句
正确的Laravel Eloquent/查询构造器写法
针对你需要转换的原生SQL,以下几种写法都可以实现需求:
1. 使用selectRaw直接编写原生字段逻辑
这是最直接的方式,完全对应你的原生SQL:
$chats = DB::table('chats') ->selectRaw('`from`, `to`, `from` + `to` as total') ->get();
2. 使用DB::raw配合select拆分字段
如果需要将原生计算逻辑单独拆分,也可以这么写:
$chats = DB::table('chats') ->select('from', 'to', DB::raw('`from` + `to` as total')) ->get();
3. 基于Eloquent模型的写法(假设模型名为Chat)
如果项目中定义了对应的Eloquent模型,直接调用模型的查询方法即可:
// 用selectRaw的方式 $chats = Chat::selectRaw('`from`, `to`, `from` + `to` as total') ->get(); // 或者用DB::raw配合select $chats = Chat::select('from', 'to', DB::raw('`from` + `to` as total')) ->get();
注意点
from是MySQL的保留关键字,必须用反引号(`)包裹,否则会触发语法错误,这可能是你之前尝试失败的原因。
内容的提问来源于stack exchange,提问作者Kittu_kix
相关产品推荐
相关产品推荐

