Friday, March 31, 2017

Laravel - how to know if the attribute exists in relacional table

im doing a property sales website, and i have todo an advanced search, with number of bedroom for example.

but i have properties like shop that dont have bedroom attributes,how to know each table i have to search like apartment or house. i'm using scopes and for location and type of properties works fine.

My property model

public function atributos(){
        //se for moradia
        if ($this->tipoimovel_id == 1) {
            return $this->hasOne(Moradia::class);
        }
        //se for apartamento
        else if ($this->tipoimovel_id == 2) {            
            return $this->hasOne(Apartamento::class);
        }
        //se for loja
        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);
        }
    }      

Warehouse dont have number of bedrooms

Schema::create('armazens', function (Blueprint $table) {
    $table->integer('imovel_id');           
    $table->integer('areaAcessoria');
    $table->integer('areaTotal');
    $table->smallInteger('anoConstrucao');
    $table->timestamps();
});

house have

Schema::create('moradias', function (Blueprint $table) {
    $table->integer('imovel_id');
    $table->integer('nrPisosConstrucao');
    $table->integer('nrQuartos');
    $table->integer('nrWcs');
    $table->integer('areaConstrucao');
    $table->integer('areaTerreno');
    $table->smallInteger('anoConstrucao');
    $table->timestamps();
});

My scope to search by number of bedrooms

public function scopeProcuraNrQuartos($query,$nrQuartos){
    if ($nrQuartos) $query->where( $this->atributos()->nrQuartos , '>=' , $nrQuartos);
} 

i know that its wrong, but exist some validation to know if that attribute exists in the table? Thanks



via D. Lopes

Advertisement