在创建范围为 laravel 的查询时使用 except

Using except when creating query with laravel scope

当我键入第二个 where 时,查询无法正常工作。 数据库行:

batch_id - sub_stage_id

我正在将子阶段发送到范围内。我希望它是 return Null 的,而不是等于 sub_stage_id

的那些
public function scopeBatchSubStageReady($query,$subStage,$stage = "Data Collection"){

    $stage_id = JRoadStage::findStageId($stage);
    $sub_stage_id = JRoadStage::findStageId($subStage);

    return $query->whereHas('roads',function (Builder $query) use($stage_id,$sub_stage_id){
        $query->items()->where(function (Builder $query) use($stage_id,$sub_stage_id){

            //substage equal null
                $query->where('stage_id',$stage_id)
                    ->whereNull('sub_stage_id')
                    ->where("is_here",true);

        })->where(function (Builder $query) use($stage_id,$sub_stage_id){

            //not equal to substage 
            $query->where('stage_id',$stage_id)
                ->where('sub_stage_id','!=',$sub_stage_id);

        });
    });
}

当我把第二个放在哪里时,它没有给出任何结果。当我不这样做时,它会给出 batch_id 1 和 2。我想要的是它只是给 batch_id 2 因为我发送了 substage。

$readyForItems = BatchItem::BatchSubStageReady("Screening")->get();
dd(readyForItems);

如何在范围方法中修复我的查询?

你需要的是whereDoesntHave。你能试试这个吗?

$query->whereHas('roads',function (Builder $query) use($stage_id,$sub_stage_id){
        $query->items()->where(function (Builder $query) use($stage_id,$sub_stage_id){
            
                $query->where('stage_id',$stage_id)
                    ->whereNull('sub_stage_id')
                    ->where("is_here",true);

        });
    })->whereDoesntHave('roads',function (Builder $query) use($stage_id,$sub_stage_id){
        $query->items()->where(function (Builder $query) use($stage_id,$sub_stage_id){
            
            $query->where('stage_id',$stage_id)
                ->where('sub_stage_id',$sub_stage_id);

        });
    });