Laravel从多个表嵌套whereIn

时间:2019-03-27 08:23:35

标签: laravel nested-query

我正在使用Laravel 5.7。如何将以下代码重写为单个嵌套查询?

我目前正在使用2个数据库查询来获取结果。我经历了stackoverflow中的一些答案,但在嵌套多个表时仍然有疑问

  $connectedParts = DB::table('part_connections as c')
          ->join('parts_master as p', 'p.id', '=', 'c.part_number_id')
          ->where('c.part_number_id', $partId)
          ->where('p.id', $partId)
          ->pluck('connected_to');

  $connectedComponents = DB::table('part_connections as pc')
                            ->join('parts_master as pm', 'pm.id', '=', 'pc.connected_to')
                            ->where('part_number_id',$partId)
                            ->where('pm.part_type','1')
                            ->whereIn('connected_to', $connectedParts)
                            ->pluck('connected_to');

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

首先在模型中正确设置您的关系,然后尝试以下查询:

//PartConnection model - add for eager loading
public function master() {
    return $this->belongsTo('PartMaster::class', 'connected_to', 'id');
}

$query = PartConnection::whereHas(‘master’, function($qry)) use ($partId) {
    $qry->where(‘parts_master.id’, $partId);
    $qry->where(‘parts_master.part_type’, 1);
});

$query->where(‘part_number_id’, $partId);

$connectedComponents = $query->get();

更新

然后尝试:

$connectedComponents = DB::table('part_connections as pc')
                        ->join('parts_master as pm', function($join) {
                            $join->on('pc.connected_to', '=', 'pm.id');
                            $join->on('pc.part_number_id', '=', 'pm.id');
                        }) //updated this - removed ;
                        ->where('part_number_id',$partId)
                        ->where('pm.part_type','1')
                        ->get();