如何在Laravel本地作用域中使用max函数实现指定关联查询需求
实现步骤
- 首先确保
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); } }
- 在
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'); }); }
- 调用方式:
直接在查询Temperature时调用作用域即可获取符合要求的集合:
$matchedTemperatures = Temperature::whereMaxReadingAboveThreshold()->get();
如果需要附加其他查询条件,直接链式调用即可:
$matchedTemperatures = Temperature::whereMaxReadingAboveThreshold() ->where('id', '>', 5) ->get();
内容的提问来源于stack exchange,提问作者Karim Harazin
相关产品推荐
相关产品推荐

