Monday, April 3, 2017

Laravel - Join two tables advaced search

Sorry for last question, I did not express my doubt in the best way Hey, i have to know the properties that have more than N number of rooms.

House model

public function imovel(){
    return $this->belongsTo(Imovel::class); //property
}

Apartment model

public function imovel(){
    return $this->belongsTo(Imovel::class); //property
}

Property model

public function atributos(){
        //se for moradia/  House
        if ($this->tipoimovel_id == 1) {
            return $this->hasOne(Moradia::class);
        }
        //se for apartamento/  Apartment
        else if ($this->tipoimovel_id == 2) {            
            return $this->hasOne(Apartamento::class);
        }
        //se for loja / SHOP
        else if ($this->tipoimovel_id == 3) {
            return $this->hasOne(Loja::class);
        }
        //se for armazem
        else if ($this->tipoimovel_id == 4) {
            return $this->hasOne(Armazem::class);
        }
        //se for terreno para construção
        else if ($this->tipoimovel_id == 5) {
            return $this->hasOne(TerrenoConstrucao::class);
        }
        // se for terreno para outros fins
        else if ($this->tipoimovel_id == 6) {
            return $this->hasOne(TerrenoOutrosFins::class);
        }
    }     

and im using scopes to search:

This scope im searching all houses that have more N number of bedrooms, but i have to search apartments too

public function scopeProcuraNrQuartosMoradia($query,$nrQuartos){
    if ($nrQuartos != 0) $query ->join('moradias','imoveis.id', '=', 'moradias.imovel_id')
                                ->where( 'nrQuartos' , '>=' , $nrQuartos);      
   }

So i created another scope to search in Apartments table and its wrong

public function scopeProcuraNrQuartosApartamento($query,$nrQuartos){
    if ($nrQuartos != 0) $query ->join('apartamentos','imoveis.id', '=', 'apartamentos.imovel_id')
                                ->where( 'nrQuartos' , '>=' , $nrQuartos);      
   }

Controller

 $imo = Imovel::procuraFinalidade($finalidade)->procuraTipo($tipo)->procuraNrQuartosMoradia($nrQuartos)->procuraNrQuartosApartamento($nrQuartos)->paginate(9);

Is there any way to do this in a single scope like doing two joins to look at the table of houses and apartments?

For example, would UNION in this case work?



via D. Lopes

Advertisement