通过Laravel中的ID计数值 [英] count values through id in laravel

查看:52
本文介绍了通过Laravel中的ID计数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

hello i am trying to count values from array. my ResidentMail table look like

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'
        ]
    ],
)

需要输出想要所以应该在计数时得到

Require Output want like so it should be get while count

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

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

here i am trying code for resulting that array

$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();
        }

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

i think i wrote wrong for it but i tried many ways still get wrong output. please help me to solve this array.

推荐答案

好,我希望它能为您提供帮助.

$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(),
                        
                    ]
    
                ];
               
            }

这篇关于通过Laravel中的ID计数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆