简体   繁体   English

Laravel 中带有 withCount 的案例陈述

[英]Case statement with withCount in Laravel

How do I achieve this kind of query in Laravel? Laravel如何实现这种查询?

Model::query()
        ->select('id')
        ->withCount(['relation_1', 'relation_2', 'relation_3'])
        ->selectRaw(
            '(CASE
WHEN relation_1_count < 0 THEN "relation 1 failed"
WHEN relation_1_count > 0 and relation_2_count < 0 THEN "relation 2 failed"
WHEN relation_1_count > 0 and relation_2_count > 0 and relation_3_count < 0 THEN "relation 3 failed"
ELSE "All relations passed"
END) AS model_status')
    ->get()

This gives the relation_1_count column that does not exist.这给出了不存在的relation_1_count列。

What is the proper approach for this kind of problem?解决此类问题的正确方法是什么?

Your count queries are aliased subqueries so you can't use the alias directly.您的计数查询是带别名的子查询,因此您不能直接使用别名。 In MySQL however you can use the alias in another subquery eg:在 MySQL 中,您可以在另一个子查询中使用别名,例如:

Model::query()
    ->select('id')
    ->withCount(['relation_1', 'relation_2', 'relation_3'])
    ->selectRaw("CASE WHEN (SELECT relation_1_count) < 0 THEN 'relation 1 failed'
                      WHEN (SELECT relation_1_count) > 0 AND (SELECT relation_2_count) < 0 THEN 'relation 2 failed'
                      WHEN (SELECT relation_1_count) > 0 AND (SELECT relation_2_count) > 0 AND (SELECT relation_3_count) < 0 THEN 'relation 3 failed'
                 ELSE 'All relations passed' END AS model_status")
->get()

though in my opinion this sort of logic to craft a presentational message is best handled by the PHP view logic.尽管在我看来,这种制作表示消息的逻辑最好由 PHP 视图逻辑处理。

Sidenote: I've not actually tried this particular one myself so let me know if it works.旁注:我实际上并没有自己尝试过这个特别的,所以如果它有效请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM