How to write inner join in Eloquent ORM in laravel?

I have tables named buildingsandflats

building table

Building_Id | Building_Name | .......| Building_Owned_By | ....

apartment 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 he does not return anything.

How can we do internal joins in Eloquent Orm (I don't want to use a free request)?

Update

Thanks for @Creator for his valuable time and help. He helps me find this. The solution is that we should use where Has , 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();
+4
source share
2 answers

Do it:

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

}

Request for creation with all apartments:

   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');
   }
}

Request to receive building information

      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();
+4

:

Flat::with(array('building'=>function($query){
    $query->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();
+1

Source: https://habr.com/ru/post/1527834/


All Articles