Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用laravel从多对多关系中选择值的雄辩查询_Laravel_Join_Eloquent - Fatal编程技术网

使用laravel从多对多关系中选择值的雄辩查询

使用laravel从多对多关系中选择值的雄辩查询,laravel,join,eloquent,Laravel,Join,Eloquent,我正在做一个项目,在两个表之间有一个多对多关系,第一个表是cities表,第二个表是checkpoints表 这个城市有许多检查站,这些检查站可能属于许多城市 到目前为止,我已经创建了一个名为checkpoint_city的新表,其中包含checkpoint_id和city_id 城市A有点X,Y,但是城市B有点X,Z 现在,我想选择属于城市A和B的唯一检查站,即X 到目前为止,我的代码是: $checkpoints = CheckPoint::select('*')->where('t

我正在做一个项目,在两个表之间有一个多对多关系,第一个表是cities表,第二个表是checkpoints表

这个城市有许多检查站,这些检查站可能属于许多城市

到目前为止,我已经创建了一个名为checkpoint_city的新表,其中包含checkpoint_id和city_id

城市A有点X,Y,但是城市B有点X,Z

现在,我想选择属于城市A和B的唯一检查站,即X

到目前为止,我的代码是:

 $checkpoints = CheckPoint::select('*')->where('type', 'n')->where('checkpoints.active', 1);

        if(! empty($request->city_ids)) {
            $cities=explode(",",$request->city_ids);

            $checkpoints = $checkpoints->crossJoin('checkpoint_city','checkpoints.id','=','checkpoint_city.checkpoint');
            $checkpoints = $checkpoints->crossJoin('cities','cities.id','=','checkpoint_city.city')->whereIn("cities.id",$cities);

            for($i=0; $i<count($cities); $i++){
                $checkpoints = $checkpoints->where("cities.id",$cities[$i]);
            }

           $checkpoints = $checkpoints->groupBy('checkpoints.id');
        }
但这对我没用,有什么帮助吗

您可以使用laravel whereHas,它检查是否存在附加条件的关系

$checkpoints = CheckPoint::where('type', 'n')
                    ->where('active', 1)
                    ->whereHas('cites', function($query){
                        $query->where('name','A');
                    })->whereHas('cites', function($query){
                        $query->where('name','B');
                    })->get();

假设您与检查点模型中的名称引用有归属关系,并且城市有名称字段

,那么您的SQL尝试看起来如何?SQL尝试是什么意思?您说您想要SQL查询。