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

如何在Laravel本地作用域中使用max函数实现指定关联查询需求

实现步骤

  1. 首先确保Temperature模型已经定义了和TemperatureReading的一对多关联:
// app/Models/Temperature.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Temperature extends Model
{
    // 其他模型配置...
    
    public function readings(): HasMany
    {
        return $this->hasMany(TemperatureReading::class);
    }
}
  1. 在Temperature模型中添加对应的查询作用域,两种实现方式可选:

方式1:直接使用原生子查询(和你给出的SQL逻辑完全匹配)

// 在Temperature模型中新增方法
public function scopeWhereMaxReadingAboveThreshold($query)
{
    return $query->whereRaw('temperatures.threshold < (
        select max(reading) 
        from temperature_readings 
        where temperature_readings.temperature_id = temperatures.id
    )');
}

方式2:使用Eloquent查询构造器实现(无需手写原生SQL,更易维护)

// 在Temperature模型中新增方法
public function scopeWhereMaxReadingAboveThreshold($query)
{
    return $query->where('threshold', '<', function ($subQuery) {
        $subQuery->selectRaw('max(reading)')
            ->from('temperature_readings')
            ->whereColumn('temperature_readings.temperature_id', 'temperatures.id');
    });
}
  1. 调用方式:
    直接在查询Temperature时调用作用域即可获取符合要求的集合:
$matchedTemperatures = Temperature::whereMaxReadingAboveThreshold()->get();

如果需要附加其他查询条件,直接链式调用即可:

$matchedTemperatures = Temperature::whereMaxReadingAboveThreshold()
    ->where('id', '>', 5)
    ->get();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 14:06:02