You need to enable JavaScript to run this app. 如何使用Laravel查询构造器编写对应SQL?可使用Laravel Eloquent实现相同结果
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Laravel查询构造器编写对应SQL?可使用Laravel Eloquent实现相同结果

方案1:使用Laravel查询构造器实现

首先确认你已经在文件顶部引入DB门面:
use Illuminate\Support\Facades\DB;
对应代码如下:

$attendanceData = DB::table('attendances')
    ->selectRaw('*, SUM(num_hr) AS total_hr, attendances.empID AS empid')
    ->leftJoin('addsalaryemployees', 'addsalaryemployees.empID', '=', 'attendances.empID')
    ->leftJoin('positions', 'positions.id', '=', 'addsalaryemployees.empPosition')
    ->groupBy('attendances.empID')
    ->orderBy('addsalaryemployees.empFirstName', 'asc')
    ->get();

注意:如果你的MySQL开启了严格模式(默认开启),上述group by写法可能触发ONLY_FULL_GROUP_BY报错。两种解决方法:

  • 在config/database.php中找到mysql配置项,将strict的值改为false
  • 把select中所有非聚合字段都加到groupBy的参数中,符合SQL规范要求

方案2:使用Eloquent实现

首先需要提前创建对应的模型,这里以Attendance(对应attendances表)、AddSalaryEmployee(对应addsalaryemployees表)、Position(对应positions表)为例:

第一步:定义模型关联

// app/Models/Attendance.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;

class Attendance extends Model
{
    protected $table = 'attendances';

    // 关联薪资员工表
    public function addsalaryEmployee()
    {
        return $this->hasOne(AddSalaryEmployee::class, 'empID', 'empID');
    }
}
// app/Models/AddSalaryEmployee.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;

class AddSalaryEmployee extends Model
{
    protected $table = 'addsalaryemployees';

    // 关联职位表
    public function position()
    {
        return $this->belongsTo(Position::class, 'empPosition', 'id');
    }
}

第二步:编写查询代码

use App\Models\Attendance;

$attendanceData = Attendance::selectRaw('*, SUM(num_hr) AS total_hr, attendances.empID AS empid')
    ->with('addsalaryEmployee.position') // 预加载关联数据,减少查询次数
    ->leftJoin('addsalaryemployees', 'addsalaryemployees.empID', '=', 'attendances.empID')
    ->leftJoin('positions', 'positions.id', '=', 'addsalaryemployees.empPosition')
    ->groupBy('attendances.empID')
    ->orderBy('addsalaryemployees.empFirstName', 'asc')
    ->get();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 13:06:03