jeudi 2 juin 2022

Laravel how to count each rows ID on tables relationship

so i have a 5 tables in my database with pivot, Countries, Cities, Shops, Users, shop_employee their relationship is this

Countries  | Cities      | Shops     | shop_employees| Users 
 id        | country_id  | city_id   |  shop_id      | id
                                        employee_id

my goal is i want to count each City, shop, employees in Country

this is my controller

class CountryController extends Controller
{
    public function country(){
       $countries = Country::with(['cities.shops.employees'])->get();
       return view('country',['countries'=>$countries]);
    }
}

this is my model Country

class Country extends Model
{
    public function cities(){
        return $this->hasMany(City::class);
    }
}

this is my model City

class City extends Model
{
    public function shops(){
        return $this->hasMany(Shop::class);
    }
}

this is my model Shops

class Shop extends Model
{
    public function employees(){
        return $this->belongsToMany(User::class,'shop_employees','shop_id','employee_id');
    }
}

this is my view

        <table class="table-fixed">
                <thead>
                  <tr>
                    <th class="py-2 px-2 border border-gray-300">Country</th>
                    <th class="py-2 px-2 border border-gray-300">City</th>
                    <th class="py-2 px-2 border border-gray-300">Shop</th>
                  </tr>
                </thead>
                <tbody>
                @foreach ($countries as $country)
                <tr >
                    <td class="py-2 px-2 border border-gray-300"></td>
                    <td class="py-2 px-2 border border-gray-300"></td>
                    <td class="py-2 px-2 border border-gray-300"></td>
                  </tr>
                @endforeach
                </tbody>
              </table>

i tried this code its working fine the City is counting


the output, in this output i want to display the count of shops and employee

enter image description here

but when im trying this code it gives me a error

  $country->cities->shops->count() or
  $country->cities->shops->employees->count() 

error: Property [shops] does not exist on this collection instance



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/mC9aetG
via IFTTT

Aucun commentaire:

Enregistrer un commentaire