count values through id in laravel

╄→尐↘猪︶ㄣ 提交于 2021-02-11 12:11:26

问题


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

this is my array look like

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.


回答1:


well, i wish it will help you.

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


来源:https://stackoverflow.com/questions/65606656/count-values-through-id-in-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!