如何才能将多列相同的id组通过? - Laravel

时间:2018-01-27 11:00:35

标签: php arrays laravel laravel-5

我的数据库如下:

id |group_id |property_id |type     |
1  |   9     |     13     |property |
2  |   9     |     14     |property |
3  |   9     |     15     |property | 
4  |   9     |     14     |variant  |
5  |   8     |     14     |property |
6  |   8     |     15     |variant  |
7  |   8     |     13     |property |

我的代码如下:

 $stock_get_property = StockPropertyTemplate::groupBy('group_id')->selectRaw('count(type) as quantity , group_id')->where('type' , 'property')->get();
        $stock_get_variant = StockPropertyTemplate::groupBy('group_id')->selectRaw('count(type) as quantity , group_id')->where('type' , 'variant')->get();

我希望对它们进行全面分组。 groupBy('group_id')by type =“property”和“variant”。如何组合两个查询?

我想要创建的数组输出如下;

id |group_id |count_property|count_variant|
1  |   9     |       3      |     1       |
2  |   8     |       2      |     1       |

我怎样才能使用Laravel?请帮帮我:(

2 个答案:

答案 0 :(得分:1)

可以通过单个查询解决此问题:

SELECT
    group_id,
    COUNT(NULLIF(type, 'variant')) as count_property,
    COUNT(NULLIF(type, 'property')) as count_variant
FROM StockPropertyTemplate
GROUP BY group_id;

或Laravel样式:

$stock_get_property_and_variant = 
    StockPropertyTemplate::groupBy('group_id')
        ->selectRaw(
            "group_id,
             COUNT(NULLIF(type, 'variant')) as count_property,
             COUNT(NULLIF(type, 'property')) as count_variant"
        )
        ->orderBy('id', 'asc')
        ->get();

SQL live code here

答案 1 :(得分:0)

我的解决方案如下;

fetch(url)
    .then(response => {
        var cpyResponse = response.clone();
        console.log(cpyResponse.text());
        return response.blob()
    }
    )
    .then(blob => { return new Response(blob) })
    .then(response => {
        var cpyResponse = response.clone();
        console.log(cpyResponse.text());
        return response;
    }
    )

此代码负责我的工作。