mardi 20 février 2018

Count enum column values - Laravel, Eloquent

Below is one of the object present in array.

{  
   "id":1,
   "name":"..",
   ..
   ..
   "Relation2":[  
      {  
         "id":1,
         "name": "..."
         "Relation3":[  
            {  
               "id":2,
               ..
               ..
               "pivot":{  
                  "pivot_col1":1,
                  "pivot_col1":2,
                  "is_reg":"1"          //ENUM Value Check 
               }
            }
         ]
      }
   ]
}

I am trying to loop through Relation3 objects and do a count++ if pivot column is_reg is 1 but for some reason regardless the value I get the count.

Meaning, if is_reg = "1" or "0" count results to +1. The reason is_reg values is in double quotes because the data-type is enum.

How to do a check when using enum and count++?

my code

  $total = 0;
    foreach($Relation1 as $rel1){
        foreach($rel1->Relation2 as $rel2 ){
            foreach($rel2->Relation3 as $rel3){
                if($rel3->wherePivot('is_reg', '1')){
                    $total += 1;
                }
            }
        }
    }

I also tried:

$Relation = Relation1::with(['relation2', 'relation2.relation3' => function($query){
  $query->select( DB::raw('SUM(is_reg) as total'))->wherePivot('is_reg', '1');
}]);

I tried with and without single or double quotes but I guess my checks are simply adding +1 to count when if object is present in Relation3.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire