mercredi 17 août 2022

Laravel Eloquent Relationship query with whereHas retrieve data

I have the following models in my application(Laravel):

class City extends Model {
  public function travels(){
    return $this->belongsToMany('App\models\Travel');
  }
}

class Travel extends Model {
   public function cities(){
     return $this->belongsToMany('App\models\City');
   }
   public function deals(){
     return $this->hasMany('App\models\Deal');
   }
}

I have the following table layout:

cities:

  • id
  • name

travels:

  • id
  • description

city_travel:

  • id
  • city_id
  • travel_id

deals:

  • id
  • travel_id

Now I want to display all the names of the cities with the count of travels where have deals (I not only want the cities which have only travels but these travels must also have deals) I hope I have explained my need well.

I tried only to retrieve the cities that have travels, with the code below but I'm stuck here :

$cities = City::whereHas('travels')-get();

Thanks for your help!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire