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

如何将指定原生SQL转换为Laravel数据库查询构造器写法

Laravel数据库查询构造器等价实现代码

你可以直接使用以下查询构造器代码,和给出的原生SQL逻辑完全一致:

use Illuminate\Support\Facades\DB;

$notifyList = DB::table('notifications')
    ->distinct()
    ->select(
        'notifications.id',
        'users.firstname',
        'users.lastname',
        'notifications.created_at',
        'notifications.read'
    )
    ->leftJoin('users', 'users.id', '=', 'notifications.user_id')
    ->leftJoinSub(
        DB::table('friends')->select('is_accepted', 'friend_id'),
        'fnds',
        fn($join) => $join->on('fnds.friend_id', '=', 'notifications.user_to_notify')
    )
    ->where('notifications.user_to_notify', 5)
    ->groupBy(
        'notifications.id',
        'users.firstname',
        'users.lastname',
        'notifications.created_at',
        'notifications.read',
        'fnds.is_accepted'
    )
    ->orderBy('notifications.created_at')
    ->get();

写法说明

  • distinct() 方法直接对应原生SQL的DISTINCT去重规则
  • leftJoinSub() 是Laravel内置的子查询关联方法,专门用于处理SQL中对friends表做子查询后左联的场景,不需要手写多余原生SQL片段
  • 其余leftJoin、where、groupBy、orderBy方法的参数顺序、字段规则和原生SQL完全对齐,直接调用即可

旧版本兼容方案

如果你使用的是Laravel 6以下没有leftJoinSub快捷方法的版本,可以替换为原生SQL片段定义子查询,效果完全一致:

// 替换leftJoinSub部分的代码即可
->leftJoin(
    DB::raw('(SELECT is_accepted,friend_id FROM friends) AS fnds'),
    fn($join) => $join->on('fnds.friend_id', '=', 'notifications.user_to_notify')
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 20:42:17