You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将SQL查询语句转换为Eloquent ORM语句?

嘿,我来帮你把SQL转换成Laravel的Eloquent语法!不过看起来你没附上具体的SQL语句,那我就拿一个常见的查询例子来演示转换过程,你可以照着这个思路套用到你的实际SQL上~

SQL转Eloquent示例演示

假设我们有这样一段SQL查询:

SELECT users.name, posts.title, comments.body
FROM users
JOIN posts ON users.id = posts.user_id
LEFT JOIN comments ON posts.id = comments.post_id
WHERE users.created_at >= '2023-01-01'
AND posts.status = 'published'
ORDER BY posts.created_at DESC
LIMIT 10;

对应的Eloquent写法可以是这样的:

$results = User::select('users.name', 'posts.title', 'comments.body')
    ->join('posts', 'users.id', '=', 'posts.user_id')
    ->leftJoin('comments', 'posts.id', '=', 'comments.post_id')
    ->where('users.created_at', '>=', '2023-01-01')
    ->where('posts.status', 'published')
    ->orderBy('posts.created_at', 'desc')
    ->limit(10)
    ->get();

如果你的模型之间已经定义了关联关系(比如User模型有posts()关联,Post模型有comments()关联),还可以用更简洁的关联写法:

$results = User::with(['posts.comments' => function ($query) {
        $query->select('body', 'post_id');
    }])
    ->select('name', 'id')
    ->where('created_at', '>=', '2023-01-01')
    ->whereHas('posts', function ($query) {
        $query->where('status', 'published');
    })
    ->orderBy('posts.created_at', 'desc')
    ->limit(10)
    ->get();

转换核心思路

  • 用模型类(比如User)代替FROM子句中的表名
  • SELECT对应select()方法,按需指定需要的字段
  • JOIN/LEFT JOIN对应join()/leftJoin()方法,参数依次是关联表名、关联条件
  • WHERE条件对应where()方法,多条件可链式调用
  • ORDER BY对应orderBy(),指定字段和排序方向
  • LIMIT对应limit()方法,最后用get()获取结果集(单条结果用first())

要是你把具体的SQL语句贴出来,我可以帮你精准转换哦!

内容的提问来源于stack exchange,提问作者BillO

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:52:12