Laravel: how to use derived tables / subqueries in the laravel query builder

后端 未结 1 1413
Happy的楠姐
Happy的楠姐 2020-12-09 05:09

Edit:

Though this question originally was specific for the query I\'m describing underneath, the answer I got applies to almost all questions relate

相关标签:
1条回答
  • 2020-12-09 05:40

    Your first try looks pretty close. Try this:

    I removed the long namespace reference and suggest you add a use statement to make your code more readable

    $productIds = [ 1, 2, 3, 4, 5 ];
    
    $subQuery = DB::table('attribute_options AS counted')->selectRaw('counted.id, counted.attribute_id, counted.value, count(counted.attribute_id) AS product_count')
                    ->whereIn('counted.product_id', $productIds)
                    ->groupBy('counted.attribute_option_id')
    
    $query = AttributeOption::selectRaw('IFNULL(counted.product_count, 0) AS product_count, uncounted.value, uncounted.attribute_id, uncounted.attribute_option_id')
                    ->from(\DB::raw(' ( ' . $subQuery->toSql() . ' ) AS counted '))
                    ->mergeBindings($subQuery->getQuery())
                    ->rightJoin('attribute_options AS uncounted', 'counted.id', '=', 'uncounted.id')
                    ->groupBy('attribute_option_id')
                    ->get();
    
    0 讨论(0)
提交回复
热议问题