user3518835
user3518835

Reputation: 115

How to use where clause on multiple nested eager loading in Laravel 5.8.2

I have four tables that are having relationships form the first to the last where users is a parent to village on applicant_id , Village to Cell on village_id , Cell to Sector on cell_id

and my eloquent query is as follows and it works perfectly without a where clause, when where clause is added I get an error: Column not found: 1054 Unknown column 'applicant_id' in 'where clause'

      // joins users , village ,cell and  sector
          $uvcsector = SectorApproval::with('Cell.Village.UserApplicant')
            ->where('applicant_id', 10)
        -> get();

Models :

        class Users extends Model
    {
   protected $table ="users";
    public function VillageApplicant(){
    return $this->hasMany(VillageApproval::class);
   }
 }


class VillageApproval extends Model
  {
  protected $table ="villageapplication";
     // OnetoOne relationship inverse
     public function UserApplicant()
    {
        return $this->belongsTo(Users::class, 'applicant_id');
   }

   // One Village application can be sent in one cell  (OnetoOne)
    public function Cell(){
       return $this->hasOne(CellApproval::class);
    }
  }


 class CellApproval extends Model
   {
  protected $table ="cellapplication";
    // OnetoOne relationship inverse
    public function Village()
    {
   return $this->belongsTo(VillageApproval::class, 'village_id');
   }
   // One Cell application can be sent in one sector  (OnetoOne)
   public function Sector(){
    return $this->hasOne(SectorApproval::class);
   }
  }


class SectorApproval extends Model
  {
   protected $table ="sectorapplication";
   // OnetoOne relationship inverse
   public function Cell()
   {
   return $this->belongsTo(CellApproval::class, 'cell_id');
  }
   }

Upvotes: 0

Views: 544

Answers (2)

zahid hasan emon
zahid hasan emon

Reputation: 6233

Use whereHas to search in the related tables.

$uvcsector = SectorApproval::with('Cell.Village.UserApplicant')
            ->whereHas('Cell.Village.UserApplicant', function($query) use ($id){
                $query->where('applicant_id', $id);
            })
            -> get();

Upvotes: 1

Paul Carlo Tordecilla
Paul Carlo Tordecilla

Reputation: 60

->where('village.application_id', 10)

Upvotes: 0

Related Questions