How to write a inner join in Eloquent ORM in laravel?

laravel, laravel-4, php

Solution

Do this :

class Building extends Eloquent {
protected $primaryKey = "Building_Id";
protected $table = 'buildings';
.......
.......
public function flat()
{
    return  $this->HasMany('Flat', 'Fk_Building_Id', 'Building_Id');
}

}

Query to get building with all flats:

   Building::with('flat')->(some_condition)->get();




class Flat extends Eloquent {
   protected $primaryKey = "Flat_Id";
    protected $table = 'flats';
   .......
   .......
  public function building() {
     return $this->HasOne('Building','Fk_Building_Id', 'Building_Id');
   }
}

Query to get flat with building info

      Flat::with('building')
          ->where('Building_Owned_By', '=',Auth::user()->Login_Id)         
          ->orderBy('Flat_Name')
          ->get(array('Flat_Id as flatId', 'Flat_Name as flatName'))
          ->toArray();

Problem

I have a tables named `buildings` and `flats` buildings table ``` Building_Id | Building_Name | .......| Building_Owned_By | .... ``` flats table ``` Flat_Id | Flat_Name | ........| Fk_Building_Id | ..... ``` and in My Models Building ``` class Building extends Eloquent { protected $primaryKey = "Building_Id"; protected $table = 'buildings'; ....... ....... public function flat() { return $this->hasMany('Flat', 'Fk_Building_Id', 'Building_Id'); } } ``` Flat ``` class Flat extends Eloquent { protected $primaryKey = "Flat_Id"; protected $table = 'flats'; ....... ....... public function building() { return $this->belongsTo('Building','Fk_Building_Id', 'Building_Id'); } } ``` and in my controller ``` $flats = Flat::where('Fk_Building_Id', '=',$buildingid) ->where('Building_Owned_By', '=',Auth::user()->Login_Id) ->orderBy('Flat_Name') ->get(array('Flat_Id as flatId', 'Flat_Name as flatName')) ->toArray(); ``` But it returns nothing. How can we perform inner joins in Eloquent Orm (I dont want to use fluent query)? Update Thanks for @Creator for his valuable time and help. He helps me a lot for finding this. The solution is we have to use whereHas and we rewrite the code as ``` $flats = Flat::whereHas('building', function($q){ $q->where('Building_Owned_By', '=',Auth::user()->Login_Id); }) ->where('Fk_Building_Id', '=',$buildingid) ->orderBy('Flat_Name') ->get(array('Flat_Id as flatId', 'Flat_Name as flatName')) ->toArray(); ```

Original source