【问题标题】:count values through id in laravel在laravel中通过id计算值
【发布时间】:2021-04-12 20:12:33
【问题描述】:

你好,我正在尝试从数组中计算值。 我的 ResidentMail 表看起来像

id   resident_id  mail_type
1       10          message
2       10          wellness
3       10          message
4       11          wellness
5       11          wellness
6       11          message

这是我的数组的样子

array(

    [0] => [
        [0] => [
          'id' => 1
          'resident_id' => 10
          'mail_type' => 'message'
        ],
        [1] => [
          'id' => 2
          'resident_id' => int 10
          'mail_type' => 'wellness'
        ],
        [2] => [
          'id' => 3
          'resident_id' => int 10
          'mail_type' => 'message'
        ]
    ],

    [1] => [
        [0] => [
          'id' => 4
          'resident_id' => 11
          'mail_type' => 'wellness'
        ],
        [1] => [
          'id' => 5
          'resident_id' => int 11
          'mail_type' => 'wellness'
        ],
        [2] => [
          'id' => 6
          'resident_id' => int 11
          'mail_type' => 'message'
        ]
    ],
)

要求输出想要喜欢 所以它应该在计数时得到

[10] => [
     [message] => 2,
     [wellness] => 1
],
[11] => [
     [message] => 1,
     [wellness] => 2
],
....

我正在尝试生成该数组的代码

$resident = Resident::get();
foreach ($resident as $res) {
     $residentEmail = ResidentEmail::where('resident_id', $res['id'])->get()->toArray();
     $results[] = ResidentEmail::where('resident_id', '=' , $res['id'])->where(function($query){
                   $query->where('mail_type', 'message')
                      ->orWhere('mail_type', 'wellness');
                })->count();
        }

我认为我写错了,但我尝试了很多方法仍然得到错误的输出。请帮我解决这个数组。

【问题讨论】:

  • 想要的输出...???
  • @AntonyJack 该数组是我想要的输出。我想要这样的输出
  • 您可以在 SQL 中使用 group by mail_type

标签: php arrays laravel-5


【解决方案1】:

好吧,我希望它能帮助你。

$resident = Resident::get();
            foreach ($resident as $res) {
    
                $residentEmail = ResidentEmail::where('resident_id', $res['id'])->get()->toArray();
                $a[] = [
                    $res['id'] => [
                       
                        'message' => collect($residentEmail)->where('mail_type', 'Message')->count(),
                        'wellness' => collect($residentEmail)->where('mail_type', 'Wellness')->count(),
                        
                    ]
    
                ];
               
            }

【讨论】:

    猜你喜欢
    • 2018-12-13
    • 2019-04-16
    • 2020-03-20
    • 1970-01-01
    • 2017-09-16
    • 2021-01-16
    • 1970-01-01
    • 1970-01-01
    • 2015-05-06
    相关资源
    最近更新 更多